How can I remove a click event from an element in Javascript? - javascript

I have a <div> element that has a click event attached to it using the following code:
var id = "someId";
var elem = document.getElementById("elemId");
elem.addEventListener("click", function() { someFunction(id); }, false);
At a later point I copy the element and add it to another part of the DOM, but need to first remove the click event
var elem = document.getElementById("elemId");
elem.removeEventListener("click", ???? , false);
I'm not sure how to reference the listener and so far nothing I have tried has removed the event from the element.
Any ideas?

Move the anonymous click handler function out of the addEventListener call:
var id = "someId";
var elem = document.getElementById("elemId");
var elemEventHandler = function() { someFunction(id); };
elem.addEventListener("click", elemEventHandler , false);
after which you should be able to:
var elem = document.getElementById("elemId");
elem.removeEventListener("click", elemEventHandler , false);

The answer above is correct.
However, in case, someone is looking to remove the onclick function which is attached to a button like this for eg
<button type="button" onclick="submit()" id="tour-edit-save">Save</button>
In this case, to remove the onclick attached function, one will have to remove the attribute onclick and that would work perfectly fine.
Here is how you would remove using pure JavaScript
document.getElementById('tour-edit-save').removeAttribute('onclick');
Using jquery
$('#tour-edit-save').removeAttr('onclick');
Hope this helps someone who's looking for this answer.

Related

Not able to alert/access the changed id after cloning

My code is :
var draggedElement = this.template.querySelector("[id='"+divId+"']");
var cln = draggedElement.cloneNode(true,true);
cln.classList.add('completed');
cln.classList.add('box-height');
cln.id='clone-'+divId;
event.target.appendChild(cln);
Now if I want to alert the event target id on the onclick event it gives empty result.
Trying to use like this but did not work.
const btn = this.template.querySelector("[id='clone-"+divId+"']");
btn.addEventListener('click', function(event){
console.log('Button Clicked');
console.log(event.target.id);
});
Can anyone please help? Thanks in advance.
You are probably binding the event handler before the dragged element is created (which I suppose is done in response of a user action).
Instead of playing with id attributes, just bind the event handler at the moment you add the cloned element to the document. At that time you have the reference to the cloned element, so you can just add the event listener to it.
Little, simplified, demo:
var draggedElement = document.querySelector("#test");
var cln = draggedElement.cloneNode(true,true);
cln.removeAttribute("id"); // Don't use `id`
cln.textContent = "cloned " + cln.textContent;
document.body.appendChild(cln);
cln.addEventListener('click', function(event){
console.log('Cloned button Clicked');
});
<button id="test">test</button>
Event Delegation
Although I would strongly advise against using dynamically generated id attributes, if you really require to identify elements by such id attributes, then use event delegation:
setTimeout(function () { // In reality this would be some drag event handler
var draggedElement = document.querySelector("#test");
var cln = draggedElement.cloneNode(true,true);
cln.id = "cloned-" + cln.id; // Bad practice
cln.textContent = "cloned " + cln.textContent;
document.body.appendChild(cln);
}, 500);
// Event delegation
document.body.addEventListener('click', function(event){
if (event.target.id = "cloned-test") {
console.log('Cloned button Clicked');
}
});
<button id="test">test</button>

click function triggered from div

I have got a button wrapped inside a div.
The problem is that if I click the button, somehow the click function is triggered from the div instead of the button.
Thats the function I have for the click event:
$('#ButtonDiv').on('click', '.Line1', function () {
var myVariable = this.id;
}
Thats my HTML (after is is created dynamically!!):
<div id="ButtonDiv">
<div class="Line1" id="Line1Software">
<button class="Line1" id="Software">Test</button>
</div>
</div>
So now myVariable from the click function is 'Line1Software' because the event is fired from the div instead of the button.
My click function hast to look like this because I am creating buttons dynamically.
Edit:
This is how I create my buttons and wrapp them inside the div
var c = $("<div class='Line1' id='Line1Software'</div>");
$("#ButtonDiv").append(c);
var r = $("<button class='waves-effect waves-light btn-large btnSearch Line1' id='Software' draggable='true'>Software</button>");
$("#Line1Software").append(r);
You code with the example html actually fires twice, once for each element since the event will bubble up and match both elements (since they are .Line1)
If you are trying to add an event listener to the button you should probably be using $('#Software') instead of $('#ButtonDiv')
The real problem is that neither the div nor the button have an id.
You code with the example html actually fires twice, once for each element since the event will bubble up and match both elements (since they are .Line1)
If you only want it to match the innermost element, then use return false to stop the bubbling.
$('#ButtonDiv').on('click', '.Line1', function () {
var myVariable = this.id;
console.log(myVariable);
return false;
});
var c = $("<div class='Line1' id='Line1Software'></div>");
$("#ButtonDiv").append(c);
var r = $("<button class='waves-effect waves-light btn-large btnSearch Line1' id='Software' draggable='true'>Software</button>");
$("#Line1Software").append(r);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ButtonDiv">
</div>
Your question is a bit odd because you give yourself the answer... Look at your code, you are explicitly using event delegation:
$('#ButtonDiv').on('click', '.Line1', function () {
var myVariable = this.id;
});
This code means that, for each click on a .Line1 element, the event will be delegated to the #ButtonDiv element (thanks to bubbling).
If you do not want this behavior, just do that:
$('.Line1').on('click', function () {
var myVariable = this.id;
});
This is also correct:
$('.Line1').click(function () {
var myVariable = this.id;
});

Javascript event listener firing on page load, not click event

I'm playing around with Javascript and created a class. On initializing the class, I add a button to a certain div and then add an event listener to that button for when it's clicked. What is happening though is that the function gets fired when the page loads, and not when the button is clicked. Here is my code:
function Photobank(){
this.photos;
this.addPhotoButton;
}
Photobank.prototype.init = function(){
var btn = document.createElement('button');
btn.id = "photoupload";
var t=document.createTextNode("ADD PHOTOS");
btn.appendChild(t);
this.addPhotoButton = btn;
var pb = document.getElementById('photobank');
pb.appendChild(this.addPhotoButton);
this.addPhotoButton.addEventListener("click", this.launchMediaManager(), false);
}
Photobank.prototype.launchMediaManager = function(){
alert("Launching Media Manager");
}
Am I doing something noticeably wrong?
You're calling the function rather than passing the function as an argument to addEventListener. Take the parentheses off the end of the function name:
this.addPhotoButton.addEventListener("click", this.launchMediaManager, false);
It is because you are invoking the function and setting its result as the handler to the click event, instead set the function reference as the handler.
this.addPhotoButton.addEventListener("click", this.launchMediaManager, false);

Why is jQuery .click() is skipped over?

I have a small script of javascript which iterates over a set of checkboxes which grabs the name attribute and value and then convert it to json. Then I use that value to set the href of an element and then try to trigger a click.
For some reason everything seems to function properly except for the click. I successfully change the href, I console.log() a value before the .click() and after. Everything hits except for the click. The url in the href is value as I clicked it manually.
I have my script included just before the closing body tag and have it wrapped in $(document).ready(). and I do not have duplicate ID's (I viewed the rendered source to check)
Can anyone offer some insight on this?
Here is the javascript
$(document).ready(function() {
$("#multiExport" ).on('click', function(e){
e.preventDefault();
var i = 0;
var list = new Array();
$('.appSelect:checked').each(function(){
var name = $(this).attr('name');
var id = $(this).val();
list[i] = new Array(name, id);
i++;
});
var serList = JSON.stringify(list);
console.log(serList);
var webRoot = $("#webRoot").text();
$("#exportLink").attr('href', webRoot+"/admin/admin_export_multiExport.php?emailList="+serList); //hits
console.log('1'); //hits
$("#exportLink").click(); //this line never executes
console.log('2'); //hits
});
});
$(selector).click() won't actually follow the link the way clicking on it with your mouse will. If that's what you want, you should unwrap the jquery object from the element.
$(selector)[0].click();
Otherwise, all you're doing is triggering event handlers that may or may not exist.
I may guess you need
$(document).on('click', '#multiExport', function(e){
(you can replace document by a nearest element, if you got one).
if you need dynamic click event binding.
EDIT
I would try something like that :
$(document).ready(function() {
$("#exportLink").click(function() {
window.location = $(this).attr('href');
});
$("#multiExport" ).on('click', function(e){
//whatever you want
$('#exportLink').attr('href', 'something').trigger('click');
});
});
$("#exportLink").click(); // this would launch the event.
I must admit I am very surprised that the .click() does not work.
If the idea is to load the page, then the alternative is
$(function() {
$("#multiExport" ).on('click', function(e){
e.preventDefault();
var list = [];
$('.appSelect:checked').each(function(){
var name = $(this).attr('name');
var val = $(this).val();
list.push([name, val]);
});
var serList = JSON.stringify(list);
var webRoot = $("#webRoot").text();
location=webRoot+"/admin/admin_export_multiExport.php?emailList="+serList;
});
});

addEventListener after appendChild

I create an element, eltTooltip, with document.createElement etc and add it to the DOM like this (idTooltip contains the id of eltTooltip):
document.body.appendChild(eltTooltip);
var addedElt = document.getElementById(idTooltip);
addedElt.addEventListener("click", function(){...});
Is the click event guaranteed to be added here, or is perhaps the DOM not ready for that?
Could I do this in a better way? (The page is loaded long ago so window.onload can not be used. And I can't use jQuery here.)
Your way works perfectly fine but it's probably better to attach the event listener before you add it to the DOM using eltTooltip. This saves you from fetching the element from the DOM.
Demo
var idTooltip = 'test';
var eltTooltip = document.createElement('div');
eltTooltip.innerHTML = "test"
eltTooltip.setAttribute('id', idTooltip);
eltTooltip.addEventListener("click", function () {
alert('click');
});
document.body.appendChild(eltTooltip);
You could do something like this
window.onload = function (){
var toolTip = document.createElement('div');
toolTip.innerHTML = "someData";
toolTip.addEventListener('click', myfunction);
document.body.appendChild(toolTip);
function myfunction(){
alert("hello guys ");
}
}

Categories