Raw Javascript version of .click() [duplicate] - javascript

This question already has answers here:
Pure JavaScript equivalent of jQuery click()?
(4 answers)
Closed 8 years ago.
What I have with jQuery:
if ($('#vote_c').length > 0) {
$('#vote_button').show().click();
}
I am trying to re-write it so it uses raw javascript:
if (document.getElementById('vote_c').length > 0) {
// what goes here
}

// cache lookup
var vote = document.getElementById('vote_c');
// using truthy/falsy value to determine existence
// proper test would be (vote !== null)
if (vote) {
// this is probably closest to what .show() does
// .show actually seems to track what the initial
// computed display state for the element was and
// along with .hide, toggles between the initial
// state and 'none'.
vote.style.display = '';
// mimicking .click() is done any number of ways
// but the easiest is below:
vote.onclick(); // call any registered handlers for the click event;
//
// OR (second easiest way) you could define a click event:
//
var event = new MouseEvent('click', {
"view": window,
"bubbles": true,
"cancelable": true
});
// and then "dispatch" that event to the targeted
// element which should trigger the handlers
vote.dispatchEvent(event);
}

if (document.getElementById('vote_c')) {
var btn = document.getElementById('vote_button');
btn.style.display = "inline"; //show
btn.click() //click
}

document.getElementById('vote_button').onclick = function(){
document.getElementById('vote_button').style.display = 'block';
};
Oh, my bad. I did not see the if statement, but it should point you in the right direction.

Related

Call a function in Javascript after a particular div has loaded [duplicate]

This question already has answers here:
What is the difference between a function call and function reference?
(6 answers)
How to access the webpage DOM/HTML from an extension popup or background script?
(2 answers)
Closed 14 days ago.
I am developing a Chrome plugin and I am facing a challenge where a function I call uses a variable to get element by class name. The variable returns undefined as the function gets called before the particular element is loaded in the DOM.
Please see the code below -
(() => {
let wfLeftControls;
let currentProject = "";
let dynButtons;
const newProjectLoaded = async () => {
const notesBtnExists = document.getElementsByClassName("notes-button")[0];
if (!notesBtnExists) {
const notesBtnElement = document.createElement("div");
const notesBtnSvg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
const notesBtnPath = document.createElementNS('http://www.w3.org/2000/svg', 'path');
notesBtnElement.className = "button " + "top " + "notes-button ";
/* active class highlights that the menu is active */
notesBtnSvg.setAttribute('viewBox', '0 0 45 45');
notesBtnSvg.setAttribute('fill', '#ffffff');
notesBtnSvg.classList.add('bem-Svg');
notesBtnSvg.setAttribute('style', 'display: block; position: relative;');
notesBtnPath.setAttribute('d', 'M9 39h30V20.25L27.75 9H9v30Zm0 3q-1.25 0-2.125-.875T6 39V9q0-1.25.875-2.125T9 6h20l13 13v20q0 1.25-.875 2.125T39 42Zm4.95-8.55h20.1v-3h-20.1Zm0-7.95h20.1v-3h-20.1Zm0-7.95h13.8v-3h-13.8ZM9 39V9v30Z');
notesBtnPath.setAttribute('fill', '#fffff');
notesBtnSvg.appendChild(notesBtnPath);
notesBtnElement.appendChild(notesBtnSvg);
notesBtnElement.addEventListener("click", NotesPanelEventHandler);
/* to open or close notes panel when user clicks icon */
setTimeout(() => {
wfLeftControls = document.getElementsByClassName("left-sidebar-links")[0];
wfLeftControls.appendChild(notesBtnElement);
}, 5000);
}
};
chrome.runtime.onMessage.addListener((obj, sender, response) => {
const { type, projectID } = obj;
if (type === "NEW") {
currentProject = projectID;
newProjectLoaded();
}
});
window.onload = newProjectLoaded();
})();
So here, newProjectLoaded() is the function being called.
Since the code is exectued before the element "left-sidebar-links" is loaded, the variable wfLeftControls returns undefined
So I have set a 5 second timeout to fix this problem.
Can someone please help me with how to call this function newProjectLoaded(); after all DOM elements are loaded or left-sidebar-links is loaded?
Thanks in advance 🙏
If you need to wait till DOM is ready (all elements has been added to page) use event "DOMContentLoaded".
You have been used event "load" whitch is fired after "DOMContentLoaded".
The problem is - you didn't set newProjectLoaded as event listener, you called your function and call result was setted as listener:
// change this
window.onload = newProjectLoaded(); // function was called -> return undefined -> undefined set as event handler
// to this
window.onload = newProjectLoaded; // function set as event handler

Access variable outside of an eventListener in Javascript [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I am building an app with Javascript and OpenLayers and while it's going fairly well, I am stuck at what I feel could be an easy problem for someone experienced.
Here is part the code where the problem lives :
const baseLayerElementsRight = document.querySelectorAll(
'[name="baseLayerRadioButtonRight"]'
);
let layerRender = {};
for (let baseLayerElementRight of baseLayerElementsRight) {
baseLayerElementRight.addEventListener(
'change',
function() {
let baseLayerElementValueRight = this.value;
layerGroupRight.getLayers().forEach(function(element) {
let baseLayerNameRight = element.get('title');
element.setVisible(
baseLayerNameRight === baseLayerElementValueRight
);
let elementVisibility = element.get('visible');
if (elementVisibility) {
layerRender = element;
console.log(layerRender);
}
});
},
false
);
}console.log(layerRender)
So Basically, I need to apply a method on the "layerRender" object variable outside of the event callback and I am quite new to programming and I struggle to find a solution to access the variable value
The console.log in the callback's event output the Object I want everytime I click on a given radio type input, but the console.log outisde it outputs an empty Object and of course don't update everytime I the event is happening.
How could I do to access the layerRender value outside of the callback?
Thanks a lot
your last console.log only happens once as the code runs through... you first declare the variable. Then you add an eventListener in a for loop then finally do console.log code executes. and it executes NOT when you're clicking
const baseLayerElementsRight = document.querySelectorAll(
'[name="baseLayerRadioButtonRight"]'
);
let layerRender;
for (let baseLayerElementRight of baseLayerElementsRight) {
baseLayerElementRight.addEventListener(
'change',
function() {
console.log('Click happened');
layerGroupRight.getLayers().forEach(function(element) {
let baseLayerNameRight = element.get('title');
element.setVisible(
baseLayerNameRight === this.value
);
let elementVisibility = element.get('visible');
if (elementVisibility) {
layerRender = element; // assign element to layerRender
// console.log if element is visible only
console.log(layerRender);
}
});
},
false
);
}
console.log(layerRender); // Happens when function initialise NOT when click happens

Remove all listener of "document" element [duplicate]

Just question: Is there any way to completely remove all events of an object, e.g. a div?
EDIT: I'm adding per div.addEventListener('click',eventReturner(),false); an event.
function eventReturner() {
return function() {
dosomething();
};
}
EDIT2: I found a way, which is working, but not possible to use for my case:
var returnedFunction;
function addit() {
var div = document.getElementById('div');
returnedFunction = eventReturner();
div.addEventListener('click',returnedFunction,false); //You HAVE to take here a var and not the direct call to eventReturner(), because the function address must be the same, and it would change, if the function was called again.
}
function removeit() {
var div = document.getElementById('div');
div.removeEventListener('click',returnedFunction,false);
}
I am not sure what you mean with remove all events. Remove all handlers for a specific type of event or all event handlers for one type?
Remove all event handlers
If you want to remove all event handlers (of any type), you could clone the element and replace it with its clone:
var clone = element.cloneNode(true);
Note: This will preserve attributes and children, but it will not preserve any changes to DOM properties.
Remove "anonymous" event handlers of specific type
The other way is to use removeEventListener() but I guess you already tried this and it didn't work. Here is the catch:
Calling addEventListener to an anonymous function creates a new listener each time. Calling removeEventListener to an anonymous function has no effect. An anonymous function creates a unique object each time it is called, it is not a reference to an existing object though it may call one. When adding an event listener in this manner be sure it is added only once, it is permanent (cannot be removed) until the object it was added to, is destroyed.
You are essentially passing an anonymous function to addEventListener as eventReturner returns a function.
You have two possibilities to solve this:
Don't use a function that returns a function. Use the function directly:
function handler() {
dosomething();
}
div.addEventListener('click',handler,false);
Create a wrapper for addEventListener that stores a reference to the returned function and create some weird removeAllEvents function:
var _eventHandlers = {}; // somewhere global
const addListener = (node, event, handler, capture = false) => {
if (!(event in _eventHandlers)) {
_eventHandlers[event] = []
}
// here we track the events and their nodes (note that we cannot
// use node as Object keys, as they'd get coerced into a string
_eventHandlers[event].push({ node: node, handler: handler, capture: capture })
node.addEventListener(event, handler, capture)
}
const removeAllListeners = (targetNode, event) => {
// remove listeners from the matching nodes
_eventHandlers[event]
.filter(({ node }) => node === targetNode)
.forEach(({ node, handler, capture }) => node.removeEventListener(event, handler, capture))
// update _eventHandlers global
_eventHandlers[event] = _eventHandlers[event].filter(
({ node }) => node !== targetNode,
)
}
And then you could use it with:
addListener(div, 'click', eventReturner(), false)
// and later
removeAllListeners(div, 'click')
DEMO
Note: If your code runs for a long time and you are creating and removing a lot of elements, you would have to make sure to remove the elements contained in _eventHandlers when you destroy them.
This will remove all listeners from children but will be slow for large pages. Brutally simple to write.
element.outerHTML = element.outerHTML;
Use the event listener's own function remove(). For example:
getEventListeners().click.forEach((e)=>{e.remove()})
As corwin.amber says, there are differences between Webkit an others.
In Chrome:
getEventListeners(document);
Which gives you an Object with all the existing event listeners:
Object
click: Array[1]
closePopups: Array[1]
keyup: Array[1]
mouseout: Array[1]
mouseover: Array[1]
...
From here you can reach the listener you want to remove:
getEventListeners(document).copy[0].remove();
So All the event listeners:
for(var eventType in getEventListeners(document)) {
getEventListeners(document)[eventType].forEach(
function(o) { o.remove(); }
)
}
In Firefox
Is a little bit different because it uses a listener wrapper that contains no remove function. You have to get the listener you want to remove:
document.removeEventListener("copy", getEventListeners(document).copy[0].listener)
All the event listeners:
for(var eventType in getEventListeners(document)) {
getEventListeners(document)[eventType].forEach(
function(o) { document.removeEventListener(eventType, o.listener) }
)
}
I stumbled with this post trying to disable the annoying copy protection of a news website.
Enjoy!
You can add a hook function to intercept all calls to addEventHandler. The hook will push the handler to a list that can be used for cleanup. For example,
if (EventTarget.prototype.original_addEventListener == null) {
EventTarget.prototype.original_addEventListener = EventTarget.prototype.addEventListener;
function addEventListener_hook(typ, fn, opt) {
console.log('--- add event listener',this.nodeName,typ);
this.all_handlers = this.all_handlers || [];
this.all_handlers.push({typ,fn,opt});
this.original_addEventListener(typ, fn, opt);
}
EventTarget.prototype.addEventListener = addEventListener_hook;
}
You should insert this code near the top of your main web page (e.g. index.html). During cleanup, you can loop thru all_handlers, and call removeEventHandler for each. Don't worry about calling removeEventHandler multiple times with the same function. It is harmless.
For example,
function cleanup(elem) {
for (let t in elem) if (t.startsWith('on') && elem[t] != null) {
elem[t] = null;
console.log('cleanup removed listener from '+elem.nodeName,t);
}
for (let t of elem.all_handlers || []) {
elem.removeEventListener(t.typ, t.fn, t.opt);
console.log('cleanup removed listener from '+elem.nodeName,t.typ);
}
}
Note: for IE use Element instead of EventTarget, and change => to function, and various other things.
Clone the element and replace the element with its clone. Events are not cloned.
elem.replaceWith(elem.cloneNode(true));
This uses Node.cloneNode() to clone the elem DOM object, which ignores all event handlers (though, as Jan Turoň's answer notes, attributes like onclick="…" will remain). It then uses Element.replaceWith() to replace elem with that clone. Simple assignment to an anonymous clone wasn't working for me.
This should be faster and cleaner than redefining elem.outerHTML with itself (as proposed by pabombs's answer) but may be slower than answers that iterate through and purge each listener (noting that getEventListeners() seems available exclusively in Chrome's dev console—not elsewhere in Chrome, not at all on Firefox). Presumably, at some higher volume of listeners to clear, this non-loop solution becomes faster.
(This is a simplification of Felix Kling's answer with help from asheroto's comment to it.)
you can add function and remove all other click by assign them
btn1 = document.querySelector(".btn-1")
btn1.addEventListener("click" , _=>{console.log("hello")})
btn1.addEventListener("click" , _=>{console.log("How Are you ?")})
btn2 = document.querySelector(".btn-2")
btn2.onclick = _=>{console.log("Hello")}
btn2.onclick = _=>{console.log("Bye")}
<button class="btn-1">Hello to Me</button>
<button class="btn-2">Hello to Bye</button>
You can indeed remove all event handlers by cloning the node as #FelixKling suggests in his answer, however don't forget that
attribute event handlers are not affected by cloning
Having element like this
<div id="test" onclick="alert(42)">test</div>
will still alert on click after cloning. To remove this sort of events, you need to use removeAttribute method, in general
const removeAttEvents = el =>
[...el.attributes].forEach(att =>
att.name.startsWith("on") && el.removeAttribute(att.name)
);
Then having the test element above, calling removeAttEvents(test) gets rid of the click handler.
To complete the answers, here are real-world examples of removing events when you are visiting websites and don't have control over the HTML and JavaScript code generated.
Some annoying websites are preventing you to copy-paste usernames on login forms, which could easily be bypassed if the onpaste event was added with the onpaste="return false" HTML attribute.
In this case we just need to right click on the input field, select "Inspect element" in a browser like Firefox and remove the HTML attribute.
However, if the event was added through JavaScript like this:
document.getElementById("lyca_login_mobile_no").onpaste = function(){return false};
We will have to remove the event through JavaScript also:
document.getElementById("lyca_login_mobile_no").onpaste = null;
In my example, I used the ID "lyca_login_mobile_no" since it was the text input ID used by the website I was visiting.
Another way to remove the event (which will also remove all the events) is to remove the node and create a new one, like we have to do if addEventListener was used to add events using an anonymous function that we cannot remove with removeEventListener.
This can also be done through the browser console by inspecting an element, copying the HTML code, removing the HTML code and then pasting the HTML code at the same place.
It can also be done faster and automated through JavaScript:
var oldNode = document.getElementById("lyca_login_mobile_no");
var newNode = oldNode.cloneNode(true);
oldNode.parentNode.insertBefore(newNode, oldNode);
oldNode.parentNode.removeChild(oldNode);
Update: if the web app is made using a JavaScript framework like Angular, it looks the previous solutions are not working or breaking the app.
Another workaround to allow pasting would be to set the value through JavaScript:
document.getElementById("lyca_login_mobile_no").value = "username";
At the moment, I don't know if there is a way to remove all form validation and restriction events without breaking an app written entirely in JavaScript like Angular.
Update 2: There is also a way to remove a specific event that was added with addEventListener on a website we don't own, by using the getEventListeners function combined to removeEventListener like mentioned in the answer of Jmakuc. If getEventListeners does not exist like on Firefox, you can use a polyfill and inject the script on the page with Greasemonkey addon: https://github.com/colxi/getEventListeners/issues/1
The only easy way I found and worked is this:
Let's say we want to add 2 event listeners
const element = document.getElementById("element");
element.addEventListener('mouseover',
()=>{
// some task
});
element.addEventListener('mouseout',
()=>{
// some task
});
Now you can remove both of the elements by simply:
element.replaceWith(element.cloneNode(true));
Removing all the events on document:
One liner:
for (key in getEventListeners(document)) { getEventListeners(document)[key].forEach(function(c) { c.remove() }) }
Pretty version:
for (key in getEventListeners(document)) {
getEventListeners(document)[key].forEach(function(c) {
c.remove()
})
}
angular has a polyfill for this issue, you can check. I did not understand much but maybe it can help.
const REMOVE_ALL_LISTENERS_EVENT_LISTENER = 'removeAllListeners';
proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER] = function () {
const target = this || _global;
const eventName = arguments[0];
if (!eventName) {
const keys = Object.keys(target);
for (let i = 0; i < keys.length; i++) {
const prop = keys[i];
const match = EVENT_NAME_SYMBOL_REGX.exec(prop);
let evtName = match && match[1];
// in nodejs EventEmitter, removeListener event is
// used for monitoring the removeListener call,
// so just keep removeListener eventListener until
// all other eventListeners are removed
if (evtName && evtName !== 'removeListener') {
this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, evtName);
}
}
// remove removeListener listener finally
this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, 'removeListener');
}
else {
const symbolEventNames = zoneSymbolEventNames$1[eventName];
if (symbolEventNames) {
const symbolEventName = symbolEventNames[FALSE_STR];
const symbolCaptureEventName = symbolEventNames[TRUE_STR];
const tasks = target[symbolEventName];
const captureTasks = target[symbolCaptureEventName];
if (tasks) {
const removeTasks = tasks.slice();
for (let i = 0; i < removeTasks.length; i++) {
const task = removeTasks[i];
let delegate = task.originalDelegate ? task.originalDelegate : task.callback;
this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
}
}
if (captureTasks) {
const removeTasks = captureTasks.slice();
for (let i = 0; i < removeTasks.length; i++) {
const task = removeTasks[i];
let delegate = task.originalDelegate ? task.originalDelegate : task.callback;
this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
}
}
}
}
if (returnTarget) {
return this;
}
};
....
You can add a helper function that clears event listener for example
function clearEventListener(element) {
const clonedElement = element.cloneNode(true);
element.replaceWith(clonedElement);
return clonedElement;
}
just pass in the element to the function and that's it...
Sub-class of EventTarget from the JavaScript WebAPI. Supports removing events without specifying a handler function reference.
class SmartEventTarget extends EventTarget {
constructor() {
super();
this.handlers = {};
}
addEventListener(name, handler) {
super.addEventListener(name, handler);
if (!this.handlers[name]) {
this.handlers[name] = new Set();
}
this.handlers[name].add(handler);
}
removeEventListener(name, handler) {
if (handler) {
super.removeEventListener(name, handler);
this.handlers[name].delete(handler);
} else {
this.handlers[name].forEach(h => {
super.removeEventListener(name, h)
});
this.handlers[name].clear();
}
}
removeAllListeners(name) {
if (name) {
this.removeEventListener(name, null);
} else {
Object.keys(this.handlers).map(name => {
this.removeEventListener(name, null);
});
this.handlers = {};
}
}
}
See this Gist for unit tests. You can run the tests by simply copying the code from the Gist into your browser JS console and pressing enter.
Be sure to read strange JS from the internet before blindly pasting it into your console.
https://gist.github.com/angstyloop/504414aba95b61b98be0db580cb2a3b0
I know this is an old question but for me the only thing that worked was:
parentOfTheElement.innerHTML = parentOfTheElement.innerHTML;
While the other solutions do in fact remove all the listeners, I had problems adding new ones when using either the outerHTML trick or cloneNode()
May be the browser will do it for you if you do something like:
Copy the div and its attributes and insert it before the old one, then move the content from the old to the new and delete the old?
One method is to add a new event listener that calls e.stopImmediatePropagation().
var div = getElementsByTagName('div')[0]; /* first div found; you can use getElementById for more specific element */
div.onclick = null; // OR:
div.onclick = function(){};
//edit
I didn't knew what method are you using for attaching events. For addEventListener you can use this:
div.removeEventListener('click',functionName,false); // functionName is the name of your callback function
more details

Adding / Removing Dynamically Generated Events in JavaScript

The problem I've got is trying to dynamically generate answers into pre-made boxes for a JavaScript quiz. Each answer has an index and it's the index that determines if the answer is correct (this info comes from a JSON and can't be modified). For each question, the answers are all randomised. I also have a seperate function to feed back t the user if they were right or wrong.
The approach I initally took for to use a For Loop to dynamically build each answer, but this was loading the same index into each answer (a common problem when using variables inside for loops). So I decided to add a listener to each answer and pulled this out into a seperate function to ensure each answer had it's own index. That part worked great, each had it own listener passing the index to the answer function, but when the next question was loaded two listeners had been added to the answer as it was re-generated for the next question. So, logically I added a remove listener, but this doesn't seem to work.
I know what I need to do to make this quiz work, I'm just not sure how to do it. Here's the code I have already:
Loading Answers to screen:
// Load Answers
for (i=0; i<4; i++) {
var answerBox = 'answer' + (i + 1);
app.LoadInnerHTML(answerBox, answers[i].title);
this.listenerFunc(i);
}
Adding the Listeners:
this.listenerFunc = function(j) {
var thisQuiz = this;
var answers = this.CurrentAnswers;
var answerBox = 'answer' + (j + 1);
var answerIndex = answers[j].index;
var answerElement = document.getElementById(answerBox);
// If there already is an event listener then remove it
answerElement.removeEventListener('click', function () {
thisQuiz.AnswerQuestion(answerIndex);
});
// Add New Event Listener
if (answerElement.addEventListener) { // all browsers except IE before version 9
answerElement.addEventListener("click", function () {
thisQuiz.AnswerQuestion(answerIndex);
}, false);
} else {
if (answerElement.attachEvent) { // IE before version 9
answerElement.attachEvent("click", function () {
thisQuiz.AnswerQuestion(answerIndex);
});
}
}
};
Answering the Question:
// Answer Questions
this.AnswerQuestion = function (index) {
// If Question is answered correctly
if (index == 0) {
alert('Question Answered Correctly ' + index);
} else {
alert('Question Answered Incorrectly ' + index);
}
// Call Next Question
this.LoadNextQuestion();
}
I just feel like I need to untangle everything becasue I've kept patching it to try and make it work. As a side note though I can only work with JavaScript, I can't use any frameworks like JQuery - I'm pretty sure theres a really easy solution in JQuery, but unfortunately I'm bound to just JavaScript.
The problem is with passing closure to removeEventListener. It's a completely new reference to callback so browser is not able remove it, because it's not defined in listeners list.
You need to extract somewhere outside (away from listenerFunc) a list of listeners:
this.listenerCallbacks = [];
this.listenerFunc = function(j) {
// .. head of listenerFunc
var answerIndex = answers[j].index;
if (!this.listenerCallbacks[answerIndex]) {
this.listenerCallbacks[answerIndex] = function () {
thisQuiz.AnswerQuestion(answerIndex);
}
}
var answerElement = document.getElementById(answerBox);
// If there already is an event listener then remove it
answerElement.removeEventListener('click', this.listenerCallbacks[answerIndex]);
// Add New Event Listener
if (answerElement.addEventListener) { // all browsers except IE before version 9
answerElement.addEventListener("click", this.listenerCallbacks[answerIndex], false);
} else if (answerElement.attachEvent) { // IE before version 9
answerElement.attachEvent("click", this.listenerCallbacks[answerIndex]);
}
};

remove event listener on a input in pure javascript [duplicate]

This question already has answers here:
How to removeEventListener that is addEventListener with anonymous function?
(5 answers)
Closed 6 years ago.
I an attaching event listeners in input box by using ID. so its working fine but I want to remove event listeners its will not work for me.
document.getElementById("myInput").addEventListener("keyup", function({
console.log(document.getElementById("myInput").value);
});
document.getElementById("myInput").removeEventListener("keyup",function() {
});
The second argument needs to be the event listener you want to remove (so you need to keep a reference to that function around instead of putting a function expression directly as the argument to addEventListener).
You're passing it a brand new function. It doesn't get removed, because that function wasn't listening in the first place.
var in = document.getElementById("myInput");
function myListener (event) {
console.log(in.value);
}
in.addEventListener("keyup", myListener);
in.removeEventListener("keyup", myListener);
Try that
var fn = function({
console.log(document.getElementById("myInput").value);
}
document.getElementById("myInput").addEventListener("keyup", fn);
document.getElementById("myInput").removeEventListener("keyup", fn);
var body =
document.querySelector('body'),
clickTarget =
document.getElementById('click-target'),
mouseOverTarget =
document.getElementById('mouse-over-target'),
toggle = false;
function makeBackgroundYellow() {
'use strict';
if (toggle) {
body.style.backgroundColor = 'white';
} else {
body.style.backgroundColor = 'yellow';
}
toggle = !toggle;
}
clickTarget.addEventListener('click',
makeBackgroundYellow,
false
);
mouseOverTarget.addEventListener('mouseover', function () {
'use strict';
clickTarget.removeEventListener('click',
makeBackgroundYellow,
false
);
});
target.removeEventListener(type, listener[, options]);
target.removeEventListener(type, listener[, useCapture]);
the second argument is the eventlistener you want to remove, see this

Categories

Resources