Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript event listener refresh

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.

like image 993
Michael Guantonio Avatar asked Jul 03 '13 16:07

Michael Guantonio


People also ask

How do I add an event listener to reload?

var e = document. getElementById('a'); e. addEventListener('click',location. reload);

How do you refresh using JavaScript?

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.

How do you call a function on page refresh?

User can click on refresh button, press F5 or Ctrl + R.

What is location reload?

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 )


2 Answers

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.

like image 82
DarkAjax Avatar answered Oct 02 '22 14:10

DarkAjax


As @crush mentioned, use an event delegated approach to avoid unbinding and re-binding events:

$(document).on('click', '.classElem', elm1funct);
like image 26
Johan Avatar answered Oct 02 '22 14:10

Johan