Im using .load() to populate a div with new content but when I do I have to recall all my scripts in order to use them inside the new content I beieve this is whats causing my event handlers to fire twice.
Am I wrong about that? If not is there an alternative method?
$('.user').click(function(){
if ($section !== 'users'){
$section = 'users';
$('div#contentWrapper').fadeOut(0).empty();
$('div#contentWrapper').load('pages/users.html').fadeIn(500);
}
else{
return;
}
this is the code thats apparently firing twice.
$('.addUser').click(function(){
$('.userPanel').fadeOut(0).empty();
$('.userPanel').load('pages/addUser.html').fadeIn(500);
});
I had initialy thought it was the fadeout that caused it so I set it to instant but that didnt resolve the issue. Another post on the site had recomended unbinding the click handler first but as I understand it this is a work around not a fix, and id rather fix the problem.
I am new to jquery and would really appreciate any help you guys can offer.
When you load elements dynamically, you need to use jQuery’s
.on()function to bind events to the elements that are loaded. You need to bind with.on()to an element that already exists in the DOM and usually the worst case scenario for that is the body element. If you be more specific thanbodyyou’ll usually get improved performance.For example, if you loaded a table row into a table and wanted to bind the click event on the new row, you’d use: