0

When I de-comment in the HTML, the code works properly. May I ask what the problem is and why it happened? Just started learning web programming last week, thanks a lot.

<!DOCTYPE html>
    <html lang="en">
    <html>
    <head>
        <meta charset="utf-8">
        <title>Canvas</title>
        <script src="jquery-3.3.1.js"></script>
        <script src="menu.js"></script>
        <link rel="stylesheet" type="text/css" href="style.css" />
    </head>

    <body>
        <span id="id1">Welcome back to my site. </span>
        <div id="div1" >
            <p>Hi</p>
            <a href="javascript:void(0);" id="hyper">Hi</a>
            <!--<script src="menu.js"></script> -->
        </div>
        <input type="button" id="btn" value="Toggle" />

    </body>
</html>

JavaScript (menu.js)

$("#hyper").click(function(){
    alert("Hi");
});
bird
  • 1,609
  • 11
  • 23
  • Maybe because the script will be loaded before the actual button that will trigger the function, and by that time the id "hyper" is not yet existing? – boosted_duck Mar 29 '19 at 03:04
  • wrap in jqueries be-all-end-all solution-to-almost-everything ... the *document ready* – Jaromanda X Mar 29 '19 at 03:07

2 Answers2

3

The problem is that when the <script> is in <head> its executed before the document has been loaded. It means when the <script> is in <head> and $("#hyper") line is executed at that time the element

<a href="javascript:void(0);" id="hyper">Hi</a>

is not generated. So it doesnot work.

Solution:

  • Put your <script> at end of <body>
  • Or you can use document.ready()

Below are two examples to see the difference.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
  //At this point "<div id="test"><div>" is not loaded 
  console.log($('#test').length) //0
  console.log(document.querySelector('#test')) //null
</script>

<div id="test"><div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="test"><div>

<script>
  console.log($('#test').length) //1
  console.log(document.querySelector('#test')) //<div id="test">…</div>
</script>
Maheer Ali
  • 32,967
  • 5
  • 31
  • 51
0

There are two problems with scripts in the <head>

  1. Those scripts are executed before loading of the body, sometimes this may cause problems, however you can overcome this problem using document.ready or window.onload etc.

  2. In big applications scripts become very big file, then if you've loaded them in the <head>, then user have to wait until they load fully to see anything on the webpage, but if you put them in the footer of the page, then you can create a pre-loader on the webpage, which will be loaded and shown to the user until all the scripts load completely.

Shridhar Sharma
  • 2,185
  • 1
  • 6
  • 12