0

I don't understand why JQuery is not working in the following html sample code:

The second div is working as expected when clicking on it. But the first div is not working at all with JQuery.

I have never used JQuery before, please help to explain. Thanks.


<html>
<head>
<script src="jquery.js"></script>
<script language="javascript">
     $(".header_logo").click(function () {
         alert("It doesn't work with JQuery function.");
     });
</script>
</head>
<body>
<div class="header_logo">Click with JQuery</div>
<hr/>
<div style="background-color:gray;" onclick="javascript:alert('It works with Onclick');">Click with Onclick</div>
</body>
</html>
Global
  • 17
  • 7
  • 1
    You're running your jQuery code before the elements exist on the page. Either move your jQuery to the end of the page or put it in a document ready handler. There's probably a hundred dupes here with the same problem. – j08691 Dec 19 '18 at 13:54
  • http://learn.jquery.com/using-jquery-core/document-ready/ – Rory McCrossan Dec 19 '18 at 14:02

1 Answers1

1

Because the JavaScript code is executing before the target element exists, so at the time of execution this selector finds nothing:

$(".header_logo")

Execute the code after the target element:

<html>
<head>
</head>
<body>
    <div class="header_logo">Click with JQuery</div>
    <hr/>
    <div style="background-color:gray;" onclick="javascript:alert('It works with Onclick');">Click with Onclick</div>
    <script src="jquery.js"></script>
    <script language="javascript">
        $(".header_logo").click(function () {
            alert("It doesn't work with JQuery function.");
        });
    </script>
</body>
</html>

Or, if you really want the JavaScript code in the <head> element, wrap it in a document.ready event handler so it waits until the DOM is loaded before executing:

$(function () {
    $(".header_logo").click(function () {
        alert("It doesn't work with JQuery function.");
     });
});
David
  • 176,566
  • 33
  • 178
  • 245