Search code examples
javascriptstackexecution

JavaScript Stack Execution Issue


What is wrong with my function? Why does it print many times instead of one?

$('document').ready(function(){

    //click a button dozen times it invokes submit and write message in console.log
    $('button').live('click', function(){ 
       $this = $(this);
       submit($this); //this function maybe push in stack a lot of times 
   });

});

function submit($this){
   img = $this.nextAll(".submit");

   // and when I click on image it must write one time but it writes a lot of times                                   
   img.on('click', function(){                      
      console.log($this.text() + " ----> click"); // 
   });
}

Solution

  • You should not use live, it's deprecated, you can write it in this way

    $(document).ready(function(){
        $(document).on('click', 'button', function(){ 
           img = $(this).nextAll(".submit");
           img.off('click').on('click', function(){                      
               console.log($(this).text() + " ----> click"); // 
           });
        });
    });
    

    An example using span.

    Using off unregister the previously added click events so it'll fire only once.

    Update:

    Following can replace the live. You can use the parent wrapper instead of document, read more.

    $(document).on('click', 'button', function(){ ... });