Last Updated: February 25, 2016
·
450
· dominikgarber

jQuery, fixing .click() issues adding content

(This applies to .load(), .append(), .prepend(), .html() and many other functions)

Many have used the .load() function of jQuery to update the content of the page, of a section or show another page or site without having to refresh the page or redirect the user.

But if we had a something like this:

$('#welcomeBtn').click(function(){
    alert('Welcome!');
})

$('#loadWelcome').click(function(){
     $('#someDiv').load('url.com #welcomeBtn');
})

With this, when the button is loaded, if you click it, nothing would be shown. Because the javascript(and jQuery obviously) that was loaded won't apply to the future.

To fix this you only need to change the #welcomeBtn .click() like this:

$(document).on('click', '#welcomeBtn', function(){
     alert('Welcome!');
})

This is really just a simple and maybe useless example, because we could use the .show() function, but you could load more content, when you add a comment for example and this comment has a like button.

Enjoy!