Reputation: 49
I have a widget that inserts dynamically into the web page using ajax and putting its own jquery in the header, everything works fine.
but when in that widget I paste some extra scripts to add some dynamically added elements waiting on user input, they do work fine, but the elements loaded with widget initially only get binded properly with the .click()
event whereas the dynamic elements do work but only for the first time with some very weird behavior, like triggering the click many times (evident by a call I make on that click) and then not working again altogether, what could be the reason here, is the resident script of other websites messing with my script or is it something else ?
I'm using for all the elements:
$( 'body' ).on('click', '.page_link', someFunction);
Above didn't work so i tried this which work as expected with the elements pre-loaded in the widget but not so much with dynamically added ones:
$( '.page_link' ).click(someFunction);
$( 'body' ).on('click', '.page_link', someFunction);
Any help is appreciated, thanks.
Upvotes: 0
Views: 686
Reputation: 308
You will have to use document global variable to bind click event. Try using following code :
$( document ).on('click', '.page_link', someFunction);
Upvotes: 0
Reputation: 8552
For dynamically loaded elements in jquery,You need to reapply the events(click)
As of jQuery 1.7 you can jQuery.fn.on:
$(parentSelector).on(eventName, dynamicChild, function() {});
$(parentSelector) must be a non dyanamic element
For which you can either use body
or a parent element where you appending dynamic element
Prior to jquery 1.7 you can use was to use live():
$(selector).live( eventName, function(){} );
Upvotes: 2