jquery onclick handler not called for the first click, then works

3k views Asked by At

I have a large ordered list and am using jquery to add an onclick handler to each line. This works well after the first click, but on the first click following the page load, nothing happens at all. There are no javascript errors on the page. Any suggestions please?

<ol>
<li>Line 1</li>
<li>Line 2</li>
<li>Line 3</li>
</ol>
<script>
    $(document.body).click(function () {
      $("li").each(function (i) {
        this.onclick = function() { alert(i+1); }
      });
    });
</script>
7

There are 7 answers

0
dave On BEST ANSWER

The problem is that you wrapped it in $(document.body).click so the inner code will not be executed unless you click somewhere in the page first.

Try without the $(document.body).click, should work fine.

0
Christoffer On

It's because the click event on the list items is bound when the DOM is first clicked. I think that what you mean to do, is to bind the click event when the DOM is ready:

 $(document).ready(function () {
     $("li").each(function (i) {
         this.onclick = function() { alert(i+1); }
     });
 });
1
gdoron On

Just bind the event when the DOM is ready, not after click on the body:

$(function(){
        $("li").each(function (i) {
            this.onclick = function() { alert(i+1); }
        });
});
0
Mark Schultheiss On
$("li").click(function () {
    var i = $('li').index(this);
    alert(i+1);
});

OR (uses 1.7.1 version) if the li are inserted after page is loaded.

$(document.body).on('click','li',function () { 
    var i = $('li').index(this);
    alert(i+1); 
});

Example in action: http://jsfiddle.net/MarkSchultheiss/37D5w/

0
random_user_name On

It appears you're asking for the body to be clicked before the li's get the click event bound. Further, there's a mix of jQuery and standard javascript, however I'm not addressing that here - just getting it working here:

<script>
    $(function () {
      $("li").each(function (i) {
        this.onclick = function() { alert(i+1); }
      });
    });
</script>

Note that this will wait until the body loads before running, to ensure every li is displayed and gets the event bound.

0
Jivings On

Well you're adding a click to the document, and when the document is clicked it adds the click events to the list elements. You need to get rid of the first click and change the function to a document ready:

$(document).ready(function() {
  $("li").click(function() { 
    // do something
  });
});

Also there's no need for that each loop as you can just bind to the li element.

0
Rog On

You are binding 2 click events, the first:

$(document.body).click(function () {

... triggers when the body is clicked and responds by binding new click events to the list items, hence the 2nd click response.

It's not clear what you're trying to do, but that code almost certainly isn't it. :)