Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding the event listener in javascript

Tags:

javascript

I am trying to Override the event handler of add button to update after clicking on change event button. but the code is not working

document.getElementById("test").addEventListener("click",function(){
  add();		
  document.getElementById("change_event").value="Now change the event";
  document.getElementById("change_event").style.display="block";
});

document.getElementById("change_event").addEventListener("click",function(){

  document.getElementById("test").value="Update";
  document.getElementById("change_event").style.display="none";
  
  document.getElementById("test").addEventListener("click",function(){
      update();		
  });		
});

function add(){
  alert("Add");
}
function update(){
  alert("Update");	
}
<input type="button" value="add" id="test" name="add">
<input type="button" name="change_event" style="display: none" value="change Event" id="change_event">
    	

when i click on add the add() function will call. when I clicked on Now change the event update button appear and after clicking on update button the update function must be called.

My problem is, update button calls to add() function at very first time. When I click on update then only update() must be called

like image 566
vaibhav Avatar asked Aug 12 '26 20:08

vaibhav


1 Answers

When adding events, they are stacking one on another, means you can have more than one click event on same element, so they not overwrite eachother. You must use removeEventListener to first remove previous event and only then assign new one

var eventWithAdd = function(){
    add();      
    document.getElementById("change_event").value="Now change the event";
    document.getElementById("change_event").style.display="block";

}

...

document.getElementById("test")
    .removeEventListener('click', eventWithAdd)
    .addEventListener('click', function () {update()});
like image 50
Justinas Avatar answered Aug 14 '26 12:08

Justinas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!