I have some javascript that I inherited for my job. In this javascript we have a side bar that is constantly updated(every 1 - 10 or so minutes). In the script we parse and process the AJAX from the server and then we call an interesting function.
function renewClicks(){
$('.classElem').unbind('click');
$('.classElem2').unbind('click');
$('.classElem3').unbind('click');
$('.classElem').click(elm1funct);
$('.classElem2').clikc(elm2funct);
$('.classElem3').click(elm3funct);
}
Where .classElem is a css class selector that is appended to each image that is added to the page. And elmfunct is a function that is written to handle the click. This runs on each update (deauthorizing valid already added elements and then re adding them all). I want to know if there is a way I can possibly attach a listener on the body element in the DOM so that all of the image elements added to the page and that inherit the css class will already be handled and therefore not unregistered and re-registered on each update.
Thank you for any info you can provide.
var e = document. getElementById('a'); e. addEventListener('click',location. reload);
You can use the location. reload() JavaScript method to reload the current URL. This method functions similarly to the browser's Refresh button. The reload() method is the main method responsible for page reloading.
User can click on refresh button, press F5 or Ctrl + R.
The location reload() method in HTML DOM is used to reload the current document. This method refreshes the current documents. It is similar to the refresh button in the browser. Syntax: location.reload( forceGet )
You could try this:
$('body').on('click','.classElem',elm1funct)
.on('click','.classElem2',elm2funct)
.on('click','.classElem3', elm3funct);
From jQuery's docs:
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.
As @crush mentioned, use an event delegated approach to avoid unbinding and re-binding events:
$(document).on('click', '.classElem', elm1funct);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With