Wel Wel - 7 months ago 9
Javascript Question

Why click event does not trigger?

The click event in this code does not want to trigger when I click on any li item, why is that ?

<!DOCTYPE HTML>
<html>
<head>
<!-- begin CSS -->
<!--<link href="css/style.css" type="text/css" rel="stylesheet">
<link href="css/html5-reset.css" type="text/css" rel="stylesheet">-->
<!-- end CSS -->

<!-- begin JS -->
<script src="js/jquery-2.2.3.min.js" type="text/javascript"></script>
<!--<script src="js/modernizr-2.0.6.min.js" type="text/javascript"></script>-->
<script src="js/myscript.js" type="text/javascript"></script>
<!-- end JS -->

<title>Navigation Menu</title>
</head>

<body style="background: url(images/bgnoise_lg.png) repeat left top;">
<!-- begin container -->
<div id="container" style="width: 600px; margin: 280px auto 0;">

<!-- begin navigation -->
<nav id="navigation">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Portfolio</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Blog</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
<!-- end navigation -->

</div>
<!-- end container -->

</body>
</html>


myscript.js is located under folder js:

$('#navigation li a').click(function() {
alert($(this).text());
});


I tried the code in jsfiddle and it work also when I write the script inside the index.html page it work but when I try to link to js/myscript.js it does not work !!

Answer

You need to run your script when the document is ready or you may move your script at the end, immediately before the tag closing the html body (i.e.: </body>)

Another possibility is to use event delegation, attached to document (which always exists):

    $(document).on('click', '#navigation li a', function(e) {
        alert($(this).text());
    });

$(function () { // document ready
  $('#navigation li a').click(function() {
    alert($(this).text());
  });
});
<script src="https://code.jquery.com/jquery-2.2.3.min.js" type="text/javascript"></script>

<body style="background: url(images/bgnoise_lg.png) repeat left top;">
<div id="container" style="width: 600px; margin: 280px auto 0;">

    <!-- begin navigation -->
    <nav id="navigation">
        <ul>
            <li><a href="#">Home</a></li>
            <li><a href="#">Services</a></li>
            <li><a href="#">Portfolio</a></li>
            <li><a href="#">About</a></li>
            <li><a href="#">Blog</a></li>
            <li><a href="#">Contact</a></li>
        </ul>
    </nav>
    <!-- end navigation -->

</div>

Comments