Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    Regular Coder patryk's Avatar
    Join Date
    Oct 2012
    Location
    /dev/couch
    Posts
    398
    Thanks
    2
    Thanked 64 Times in 64 Posts

    jquery .click() issue

    hi.
    i'm having hard time with binding events in dynamically loaded elements...
    i wrote this function:
    Code:
    function bindLinks(){
    	console.log('binding');
    	$('#ajaxDiv > a').click(function(ev){
    		ev.preventDefault();
    		otherFunction();
    	});
    }
    and now. i'm loading contents with number of links to 'ajaxDiv', then bindLinks() function is triggered (and it works).
    but when i empty contents of 'ajaxDiv', load new stuff and bindLinks() is called again, events are not being assigned.
    i know function is called since i get console output every time.
    any idea how to fix it?

  • #2
    The fat guy next door VIPStephan's Avatar
    Join Date
    Jan 2006
    Location
    Halle (Saale), Germany
    Posts
    8,789
    Thanks
    6
    Thanked 1,022 Times in 995 Posts
    Try on('click', function(ev) {…})

  • Users who have thanked VIPStephan for this post:

    patryk (11-03-2012)

  • #3
    Regular Coder patryk's Avatar
    Join Date
    Oct 2012
    Location
    /dev/couch
    Posts
    398
    Thanks
    2
    Thanked 64 Times in 64 Posts
    thanks
    if someone will look for that, here's working one (with 'parent > child' selection):
    Code:
    function bindLinks(){
    	$('#ajaxDiv').on('click', 'a', function(ev){
    		ev.preventDefault();
    		otherFunction();
    	});
    }

  • #4
    Senior Coder DanInMa's Avatar
    Join Date
    Nov 2010
    Location
    Salem,Ma
    Posts
    1,577
    Thanks
    13
    Thanked 248 Times in 248 Posts
    if you are calling this function mutiple times on the same page , you dont need to. If you put the .on function in in a dom ready block it will do it's thin automatically even if you add or remove anchor links from the div dynamically. lik so:

    Code:
    $(function(){	
      $('#ajaxDiv').on('click', 'a', function(ev){
    		ev.preventDefault();
    		otherFunction();
    	});
    });


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •