godlamp godlamp - 26 days ago 7
HTML Question

Cannot get the most basic click event binding to work

I am new to javascript, and I have tried to debug as much as I can but I still cannot figure why I cannot get the alert "Event 1" to show up when I click on text:

<!DOCTYPE html>
<html>

<head>
<title>Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<script type="text/javascript" language="javascript">


$("#id").bind("click", function() {
alert("Event 1");
});

</script>

<body>
<div class="foo" id="id">Click</div>
</body>
</html>

Answer Source

The problem is that you need to ensure that you only bind to the element once the page has loaded, and the element is therefore accessible. This can be done by wrapping your existing jQuery in a $(document).ready(), as can be seen in the following working example.

Also, note that .bind() has been deprecated as of jQuery 3.0, and you should use .on() instead. Note that the elements that you target with .on must exist at the time that you make the call to them:

Event handlers are bound only to the currently selected elements; they must exist at the time your code makes the call to .on()

If your target element is not visible in the DOM on page load, you can use event delegation to bind to an element that is visible on page load, and then delegate that functionality to the target.

<!DOCTYPE html>
<html>

<head>
  <title>Title</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<script type="text/javascript" language="javascript">
  $(document).ready(function() {
    $("#id").on("click", function() {
      alert("Event 1");
    });
  });
</script>

<body>
  <div class="foo" id="id">Click</div>
</body>

</html>

Hope this helps! :)