remove event listeners with extra arguments - javascript

Here is the event listener I'm using:
const eventHandler = (word, e) => {
if(isAnimating && duplicates.includes(word.innerHTML)) return;
if(String.fromCharCode(e.which) == word.innerHTML && !distWords.includes(word)) {
move(word);
}
}
words.forEach(word => {
window.addEventListener("keypress", eventHandler.bind(null, word));
});
The issue is I'm unable to remove the listener, I used something like this with no luck:
removeIT = () => {
words.forEach(word => {
window.removeEventListener("keypress", eventHandler.bind(null, word));
});
}
How can I remove the listers effectivly?

If you want to continue with this pattern you will need to store references to each bound function and iterate over them to remove the listeners.
const words_listeners = [];
words.forEach(word => {
const handler = eventHandler.bind(null, word);
window.addEventListener("keypress", handler);
words_listeners.push(handler);
});
removeIT = () => {
words_listeners.forEach(handler => {
window.removeEventListener("keypress", handler);
});
}
The snippet below is attaching click listeners to buttons, so it is necessary to also store the element that the listener is attached to, but in your case, since you're attaching to the window, you won't need to. Basically, in the loop in which you are attaching the listeners, create your bound function and assign it to a variable, attach your listener with it, then push it to an array which can be used to remove the listeners later.
const buttons = document.querySelectorAll('.word')
const word_listeners = [];
const eventHandler = (word, e) => {
console.log(word)
}
buttons.forEach(button => {
const handler = eventHandler.bind(null, button.textContent);
button.addEventListener('click', handler);
word_listeners.push([button, handler]);
});
function remove_listeners() {
word_listeners.forEach(([button, handler]) => button.removeEventListener('click', handler));
}
document.getElementById('remove').addEventListener('click', remove_listeners);
<button type="button" class="word">One</button>
<button type="button" class="word">Two</button>
<button type="button" class="word">Three</button>
<button type="button" id="remove">Remove listeners</button>

I don't think it needs to be that complicated. If you call a function that returns a closure that acts the listener you don't need any binding.
I've had to use buttons here because I don't know what your markup is like.
const buttons = document.querySelectorAll('button');
function handleClick() {
console.log(this);
}
function removeAllListeners(buttons) {
buttons.forEach(button => {
button.disabled = true;
button.removeEventListener('click', handleClick);
});
}
function handler(word) {
console.log(word);
return handleClick;
}
buttons.forEach(button => {
const { textContent } = button;
button.addEventListener('click', handler(textContent), false);
});
setTimeout(removeAllListeners, 5000, buttons);
button { background-color: #efefef; cursor: pointer; }
button:disabled { background-color: #ffb3b3; cursor: default; }
<button>Tree</button>
<button>Giant</button>
<button>Billy Joel</button>

Related

Vanilla JS remove eventlistener in currying function

I have a very "simple" vanillaJS problem. How can I remove event listener in loop inside a currying function? This just an example of my current solution where I actually need multiple parameters coming to the listener. I suspect that the event listener is not removed due to anonymous callback if I am right? How can I fix this? Example here https://codepen.io/shnigi/pen/wvPwqVR
const setEventListener = (buttons) => (event) => {
const buttonValue = event.target.value;
console.log('Eventlistener exists', buttonValue)
buttons.forEach(button => button.removeEventListener('click', setEventListener));
};
const buttons = document.querySelectorAll('button');
buttons.forEach(button => button.addEventListener('click', setEventListener(buttons)));
// Works as expected, listener is named
const testbutton = document.getElementById('kek');
const testListener = () => {
console.log('I show up only once');
testbutton.removeEventListener('click', testListener);
};
testbutton.addEventListener('click', testListener);
<button value="1">press me</button>
<button value="2">press me</button>
<button id="kek">eventlistener removed on click</button>
I suspect that the event listener is not removed due to anonymous callback if I am right?
Yes, that is a problem.
So you have to assigned anonymous function to variable and use it to remove event listener.
Here is sample code for you.
const setEventListener = (buttons: NodeList) => {
const returnedFunc = (event: Event) => {
const buttonValue = (event.target as HTMLButtonElement).value;
console.log('Eventlistener exists', buttonValue)
buttons.forEach(button => button.removeEventListener('click', returnedFunc));
};
return returnedFunc;
};
const buttons: Nodelist = document.querySelectorAll('button');
buttons.forEach(button => button.addEventListener('click', setEventListener(buttons)));
// Works as expected, listener is named
const testbutton = document.getElementById('kek');
const testListener = () => {
console.log('I show up only once');
testbutton.removeEventListener('click', testListener);
};
testbutton.addEventListener('click', testListener);
If you don't care about Internet Explorer support, you can remove anonymous event listeners in more elegant way using AbortController. Pass signal option to addEventListener() and call AbortController's abort() method when you want to remove event listener:
var listenersRemover = new AbortController();
button.addEventListener('click', callback, {signal: listenersRemover.signal}));
listenersRemover.abort();
Note: you should "rearm" abort controller to use the same signal for the new addEventListener() calls. Just initialize it again with new AbortController().
var listenersRemover = new AbortController();
const setEventListener = (buttons) => (event) => {
const buttonValue = event.target.value;
console.log('Eventlistener exists', buttonValue)
// buttons.forEach(button => button.removeEventListener('click', setEventListener));
};
const buttons = document.querySelectorAll('button');
buttons.forEach(button => button.addEventListener('click', setEventListener(buttons), {signal: listenersRemover.signal}));
// Works as expected, listener is named
const testbutton = document.getElementById('kek');
const testListener = () => {
console.log('I show up only once');
//testbutton.removeEventListener('click', testListener);
listenersRemover.abort();
};
testbutton.addEventListener('click', testListener, {signal: listenersRemover.signal});
<button value="1">press me</button>
<button value="2">press me</button>
<button id="kek">eventlistener removed on click</button>

How to remove a single function from click event listener that has multiple functions, using Javascript?

Using Javascript, how do you remove a single function from a "click" event listener, after the first click event, when there are multiple functions being used on the element with the "click" event listener? Here, after the first click, only toggleView() should remain and renderList() should be removed.
const button = document.getElementById("view_button");
button.addEventListener("click", () => {
toggleView(); // want to keep this indefinitely
renderList(); // want to remove this after the first click
button.removeEventListener("click", renderList);
});
You need to add both separately, and specify { once: true } on the one you want removed after first execution.
See MDN:
once
A boolean value indicating that the listener should be invoked at most once after being added. If true, the listener would be automatically removed when invoked.
function toggleView() {
console.log('toggleView');
}
function renderList(evt) {
console.log('renderList');
}
const button = document.getElementById("view_button");
button.addEventListener("click", toggleView);
button.addEventListener("click", renderList, { once: true });
<button type="button" id="view_button">Click</button>
You can add two event listeners and remove the one
function toggleView() {
console.log('toggleView');
}
function renderList(evt) {
evt.currentTarget.removeEventListener("click", renderList);
console.log('renderList');
}
const button = document.getElementById("view_button");
button.addEventListener("click", toggleView);
button.addEventListener("click", renderList);
<button type="button" id="view_button">Click</button>
or you can just add logic to determine if the function should be run.
function toggleView() {
console.log('toggleView');
}
function renderList() {
console.log('renderList');
}
const button = document.getElementById("view_button");
button.addEventListener("click", () => {
toggleView();
if (!button.dataset.clicked) {
renderList();
button.dataset.clicked = '1';
}
});
<button type="button" id="view_button">Click</button>
I would use a closure here to keep track of if the item has been clicked.
const button = document.getElementById("view_button");
function toggleView() {
console.log('Toggle View');
}
function renderList() {
console.log('Render List');
}
function clickHandler() {
let hasBeenClicked = false;
return function () {
toggleView();
if (!hasBeenClicked) {
renderList();
hasBeenClicked = true;
}
};
}
button.addEventListener("click", clickHandler());
<button id="view_button" type="button">View Button</button>

Javascript dot function with event handlers

Question
How do I create a custom javascript dot function that does the same thing as the following code in jQuery:
$(document).on("click touchstart", ".someClass", function() {
// code goes here
});
I'd like to declare it like this:
$(".someClass").onClick(function () {
// code goes here
});
It needs to:
work with dynamically created elements (hence jQuery .on() instead of .click())
work with computer clicks as well as touch taps
ideally, but not mandatorily, it would be written in pure javascript (no jQuery in the prototype itself, but can still be accessed through jQuery)
What I've Tried
Object.prototype.onClick = function() {
$(document).on('click touchstart', this, arguments);
};
But I receive the following error in chrome console:
Uncaught TypeError: ((n.event.special[g.origType] || {}).handle || g.handler).apply is not a function
I think I'm declaring it incorrectly, and perhaps that this is also not the correct way to access events in javascript.
You are looking for Event Delegation this allows you too dynamically add elements and still have them respond to click.
const getDiv = (name) => {
if (Array.isArray(name) === false) name = [name];
let div2 = document.createElement('div');
name.forEach(n => div2.classList.add(n));
div2.innerText = `${name}`;
return div2;
};
const makeDivs = () => {
const div = document.querySelector('#main');
const {
dataset: {
count: x
}
} = div;
for (let i = 0; i < x; i++) {
div.appendChild(getDiv('div2'));
div.appendChild(getDiv('div3'));
div.appendChild(getDiv(['div2', 'div3']));
}
};
document.addEventListener('click', ({
target
}) => {
if (target.matches('.div2')) console.log('You clicked a DIV2');
if (target.matches('.div3')) console.log('You clicked a DIV3 !!')
if (target.matches('button')) makeDivs();
});
div {
border: 1px solid red;
margin: 5px;
}
<div id='main' data-count="10">
</div>
<button>Click Me!!!</button>
Wrapping this up into a custom function.
NOTE: I changed selector param to be an array, this allows you to pass complex selectors e.g. div.myClass li:hover
const getDiv = (name) => {
if (Array.isArray(name) === false) name = [name];
let div2 = document.createElement('div');
name.forEach(n => div2.classList.add(n));
div2.innerText = `${name}`;
return div2;
};
const makeDivs = () => {
const div = document.querySelector('#main');
const {
dataset: {
count: x
}
} = div;
for (let i = 0; i < x; i++) {
div.appendChild(getDiv('div2'));
div.appendChild(getDiv('div3'));
div.appendChild(getDiv(['div2', 'div3']));
}
};
document.on = (eventType, selector, callback) => {
const events = eventType.split(' ');
const selectors = (Array.isArray(selector)) ? selector : [selector];
events.forEach(event => { document.addEventListener(event, (e) => {
if(selectors.some(s => e.target.matches(s))) callback(e);
});
});
};
// Convenience method.
document.onClick = (selector, callback) => document.on('click', selector, callback);
// Simple
document.on('click', 'button', () => makeDivs());
document.on('click', '.div2', ({target}) => console.log('You clicked a DIV2'));
// Multi Event
document.on('click touchstart', '.div3', () => console.log('You clicked a DIV3'));
// Multi selectors
document.on('click', ['.div2', '.div3'], ({target}) => console.log('You clicked. !!'));
document.onClick('div', ({target}) => console.log('A Click Event!!'));
div {
border: 1px solid red;
margin: 5px;
}
<div id='main' data-count="10">
</div>
<button>Click Me!!!</button>
So you want a .onClick jQuery method
jQuery.fn.extend({
onClick: function(sel, cb) {
return this.on('touchstart click', sel, function(evt) {
evt.preventDefault();
if (cb && typeof cb === 'function') cb.apply(this, arguments);
})
}
});
$(document).onClick('.someClass', function(ev) {
console.log(ev.type)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="someClass">CLICK ME</p>
Or this simpler variant:
$.fn.onClick = function(sel, cb) {
return this.on('touchstart click', sel, cb);
};
$(document).onClick('.someClass', function(ev) {
ev.preventDefault();
console.log(ev.type)
});

Apply multi-event do same function on same element [duplicate]

So my dilemma is that I don't want to write the same code twice. Once for the click event and another for the touchstart event.
Here is the original code:
document.getElementById('first').addEventListener('touchstart', function(event) {
do_something();
});
document.getElementById('first').addEventListener('click', function(event) {
do_something();
});
How can I compact this? There HAS to be a simpler way!
I thought some might find this approach useful; it could be applied to any similarly repetitive code:
ES6
['click','ontouchstart'].forEach( evt =>
element.addEventListener(evt, dosomething, false)
);
ES5
['click','ontouchstart'].forEach( function(evt) {
element.addEventListener(evt, dosomething, false);
});
You can just define a function and pass it. Anonymous functions are not special in any way, all functions can be passed around as values.
var elem = document.getElementById('first');
elem.addEventListener('touchstart', handler, false);
elem.addEventListener('click', handler, false);
function handler(event) {
do_something();
}
Maybe you can use a helper function like this:
// events and args should be of type Array
function addMultipleListeners(element,events,handler,useCapture,args){
if (!(events instanceof Array)){
throw 'addMultipleListeners: '+
'please supply an array of eventstrings '+
'(like ["click","mouseover"])';
}
//create a wrapper to be able to use additional arguments
var handlerFn = function(e){
handler.apply(this, args && args instanceof Array ? args : []);
}
for (var i=0;i<events.length;i+=1){
element.addEventListener(events[i],handlerFn,useCapture);
}
}
function handler(e) {
// do things
};
// usage
addMultipleListeners(
document.getElementById('first'),
['touchstart','click'],
handler,
false);
[Edit nov. 2020] This answer is pretty old. The way I solve this nowadays is by using an actions object where handlers are specified per event type, a data-attribute for an element to indicate which action should be executed on it and one generic document wide handler method (so event delegation).
const firstElemHandler = (elem, evt) =>
elem.textContent = `You ${evt.type === "click" ? "clicked" : "touched"}!`;
const actions = {
click: {
firstElemHandler,
},
touchstart: {
firstElemHandler,
},
mouseover: {
firstElemHandler: elem => elem.textContent = "Now ... click me!",
outerHandling: elem => {
console.clear();
console.log(`Hi from outerHandling, handle time ${
new Date().toLocaleTimeString()}`);
},
}
};
Object.keys(actions).forEach(key => document.addEventListener(key, handle));
function handle(evt) {
const origin = evt.target.closest("[data-action]");
return origin &&
actions[evt.type] &&
actions[evt.type][origin.dataset.action] &&
actions[evt.type][origin.dataset.action](origin, evt) ||
true;
}
[data-action]:hover {
cursor: pointer;
}
<div data-action="outerHandling">
<div id="first" data-action="firstElemHandler">
<b>Hover, click or tap</b>
</div>
this is handled too (on mouse over)
</div>
For large numbers of events this might help:
var element = document.getElementById("myId");
var myEvents = "click touchstart touchend".split(" ");
var handler = function (e) {
do something
};
for (var i=0, len = myEvents.length; i < len; i++) {
element.addEventListener(myEvents[i], handler, false);
}
Update 06/2017:
Now that new language features are more widely available you could simplify adding a limited list of events that share one listener.
const element = document.querySelector("#myId");
function handleEvent(e) {
// do something
}
// I prefer string.split because it makes editing the event list slightly easier
"click touchstart touchend touchmove".split(" ")
.map(name => element.addEventListener(name, handleEvent, false));
If you want to handle lots of events and have different requirements per listener you can also pass an object which most people tend to forget.
const el = document.querySelector("#myId");
const eventHandler = {
// called for each event on this element
handleEvent(evt) {
switch (evt.type) {
case "click":
case "touchstart":
// click and touchstart share click handler
this.handleClick(e);
break;
case "touchend":
this.handleTouchend(e);
break;
default:
this.handleDefault(e);
}
},
handleClick(e) {
// do something
},
handleTouchend(e) {
// do something different
},
handleDefault(e) {
console.log("unhandled event: %s", e.type);
}
}
el.addEventListener(eventHandler);
Update 05/2019:
const el = document.querySelector("#myId");
const eventHandler = {
handlers: {
click(e) {
// do something
},
touchend(e) {
// do something different
},
default(e) {
console.log("unhandled event: %s", e.type);
}
},
// called for each event on this element
handleEvent(evt) {
switch (evt.type) {
case "click":
case "touchstart":
// click and touchstart share click handler
this.handlers.click(e);
break;
case "touchend":
this.handlers.touchend(e);
break;
default:
this.handlers.default(e);
}
}
}
Object.keys(eventHandler.handlers)
.map(eventName => el.addEventListener(eventName, eventHandler))
Unless your do_something function actually does something with any given arguments, you can just pass it as the event handler.
var first = document.getElementById('first');
first.addEventListener('touchstart', do_something, false);
first.addEventListener('click', do_something, false);
Simplest solution for me was passing the code into a separate function and then calling that function in an event listener, works like a charm.
function somefunction() { ..code goes here ..}
variable.addEventListener('keyup', function() {
somefunction(); // calling function on keyup event
})
variable.addEventListener('keydown', function() {
somefunction(); //calling function on keydown event
})
I have a small solution that attaches to the prototype
EventTarget.prototype.addEventListeners = function(type, listener, options,extra) {
let arr = type;
if(typeof type == 'string'){
let sp = type.split(/[\s,;]+/);
arr = sp;
}
for(let a of arr){
this.addEventListener(a,listener,options,extra);
}
};
Allows you to give it a string or Array. The string can be separated with a space(' '), a comma(',') OR a Semicolon(';')
I just made this function (intentionally minified):
((i,e,f)=>e.forEach(o=>i.addEventListener(o,f)))(element, events, handler)
Usage:
((i,e,f)=>e.forEach(o=>i.addEventListener(o,f)))(element, ['click', 'touchstart'], (event) => {
// function body
});
The difference compared to other approaches is that the handling function is defined only once and then passed to every addEventListener.
EDIT:
Adding a non-minified version to make it more comprehensible. The minified version was meant just to be copy-pasted and used.
((element, event_names, handler) => {
event_names.forEach( (event_name) => {
element.addEventListener(event_name, handler)
})
})(element, ['click', 'touchstart'], (event) => {
// function body
});
I'm new at JavaScript coding, so forgive me if I'm wrong.
I think you can create an object and the event handlers like this:
const myEvents = {
click: clickOnce,
dblclick: clickTwice,
};
function clickOnce() {
console.log("Once");
}
function clickTwice() {
console.log("Twice");
}
Object.keys(myEvents).forEach((key) => {
const myButton = document.querySelector(".myButton")
myButton.addEventListener(key, myEvents[key]);
});
<h1 class="myButton">Button</h1>
And then click on the element.
document.getElementById('first').addEventListener('touchstart',myFunction);
document.getElementById('first').addEventListener('click',myFunction);
function myFunction(e){
e.preventDefault();e.stopPropagation()
do_something();
}
You should be using e.stopPropagation() because if not, your function will fired twice on mobile
This is my solution in which I deal with multiple events in my workflow.
let h2 = document.querySelector("h2");
function addMultipleEvents(eventsArray, targetElem, handler) {
eventsArray.map(function(event) {
targetElem.addEventListener(event, handler, false);
}
);
}
let counter = 0;
function countP() {
counter++;
h2.innerHTML = counter;
}
// magic starts over here...
addMultipleEvents(['click', 'mouseleave', 'mouseenter'], h2, countP);
<h1>MULTI EVENTS DEMO - If you click, move away or enter the mouse on the number, it counts...</h1>
<h2 style="text-align:center; font: bold 3em comic; cursor: pointer">0</h2>
What about something like this:
['focusout','keydown'].forEach( function(evt) {
self.slave.addEventListener(evt, function(event) {
// Here `this` is for the slave, i.e. `self.slave`
if ((event.type === 'keydown' && event.which === 27) || event.type === 'focusout') {
this.style.display = 'none';
this.parentNode.querySelector('.master').style.display = '';
this.parentNode.querySelector('.master').value = this.value;
console.log('out');
}
}, false);
});
// The above is replacement of:
/* self.slave.addEventListener("focusout", function(event) { })
self.slave.addEventListener("keydown", function(event) {
if (event.which === 27) { // Esc
}
})
*/
You can simply do it iterating an Object. This can work with a single or multiple elements. This is an example:
const ELEMENTS = {'click': element1, ...};
for (const [key, value] of Object.entries(ELEMENTS)) {
value.addEventListener(key, () => {
do_something();
});
}
When key is the type of event and value is the element when you are adding the event, so you can edit ELEMENTS adding your elements and the type of event.
Semi-related, but this is for initializing one unique event listener specific per element.
You can use the slider to show the values in realtime, or check the console.
On the <input> element I have a attr tag called data-whatever, so you can customize that data if you want to.
sliders = document.querySelectorAll("input");
sliders.forEach(item=> {
item.addEventListener('input', (e) => {
console.log(`${item.getAttribute("data-whatever")} is this value: ${e.target.value}`);
item.nextElementSibling.textContent = e.target.value;
});
})
.wrapper {
display: flex;
}
span {
padding-right: 30px;
margin-left: 5px;
}
* {
font-size: 12px
}
<div class="wrapper">
<input type="range" min="1" data-whatever="size" max="800" value="50" id="sliderSize">
<em>50</em>
<span>Size</span>
<br>
<input type="range" min="1" data-whatever="OriginY" max="800" value="50" id="sliderOriginY">
<em>50</em>
<span>OriginY</span>
<br>
<input type="range" min="1" data-whatever="OriginX" max="800" value="50" id="sliderOriginX">
<em>50</em>
<span>OriginX</span>
</div>
//catch volume update
var volEvents = "change,input";
var volEventsArr = volEvents.split(",");
for(var i = 0;i<volknob.length;i++) {
for(var k=0;k<volEventsArr.length;k++) {
volknob[i].addEventListener(volEventsArr[k], function() {
var cfa = document.getElementsByClassName('watch_televised');
for (var j = 0; j<cfa.length; j++) {
cfa[j].volume = this.value / 100;
}
});
}
}
'onclick' in the html works for both touch and click event. Here's the example.
This mini javascript libary (1.3 KB) can do all these things
https://github.com/Norair1997/norjs/
nor.event(["#first"], ["touchstart", "click"], [doSomething, doSomething]);

adding multiple event listeners to one element

So my dilemma is that I don't want to write the same code twice. Once for the click event and another for the touchstart event.
Here is the original code:
document.getElementById('first').addEventListener('touchstart', function(event) {
do_something();
});
document.getElementById('first').addEventListener('click', function(event) {
do_something();
});
How can I compact this? There HAS to be a simpler way!
I thought some might find this approach useful; it could be applied to any similarly repetitive code:
ES6
['click','ontouchstart'].forEach( evt =>
element.addEventListener(evt, dosomething, false)
);
ES5
['click','ontouchstart'].forEach( function(evt) {
element.addEventListener(evt, dosomething, false);
});
You can just define a function and pass it. Anonymous functions are not special in any way, all functions can be passed around as values.
var elem = document.getElementById('first');
elem.addEventListener('touchstart', handler, false);
elem.addEventListener('click', handler, false);
function handler(event) {
do_something();
}
Maybe you can use a helper function like this:
// events and args should be of type Array
function addMultipleListeners(element,events,handler,useCapture,args){
if (!(events instanceof Array)){
throw 'addMultipleListeners: '+
'please supply an array of eventstrings '+
'(like ["click","mouseover"])';
}
//create a wrapper to be able to use additional arguments
var handlerFn = function(e){
handler.apply(this, args && args instanceof Array ? args : []);
}
for (var i=0;i<events.length;i+=1){
element.addEventListener(events[i],handlerFn,useCapture);
}
}
function handler(e) {
// do things
};
// usage
addMultipleListeners(
document.getElementById('first'),
['touchstart','click'],
handler,
false);
[Edit nov. 2020] This answer is pretty old. The way I solve this nowadays is by using an actions object where handlers are specified per event type, a data-attribute for an element to indicate which action should be executed on it and one generic document wide handler method (so event delegation).
const firstElemHandler = (elem, evt) =>
elem.textContent = `You ${evt.type === "click" ? "clicked" : "touched"}!`;
const actions = {
click: {
firstElemHandler,
},
touchstart: {
firstElemHandler,
},
mouseover: {
firstElemHandler: elem => elem.textContent = "Now ... click me!",
outerHandling: elem => {
console.clear();
console.log(`Hi from outerHandling, handle time ${
new Date().toLocaleTimeString()}`);
},
}
};
Object.keys(actions).forEach(key => document.addEventListener(key, handle));
function handle(evt) {
const origin = evt.target.closest("[data-action]");
return origin &&
actions[evt.type] &&
actions[evt.type][origin.dataset.action] &&
actions[evt.type][origin.dataset.action](origin, evt) ||
true;
}
[data-action]:hover {
cursor: pointer;
}
<div data-action="outerHandling">
<div id="first" data-action="firstElemHandler">
<b>Hover, click or tap</b>
</div>
this is handled too (on mouse over)
</div>
For large numbers of events this might help:
var element = document.getElementById("myId");
var myEvents = "click touchstart touchend".split(" ");
var handler = function (e) {
do something
};
for (var i=0, len = myEvents.length; i < len; i++) {
element.addEventListener(myEvents[i], handler, false);
}
Update 06/2017:
Now that new language features are more widely available you could simplify adding a limited list of events that share one listener.
const element = document.querySelector("#myId");
function handleEvent(e) {
// do something
}
// I prefer string.split because it makes editing the event list slightly easier
"click touchstart touchend touchmove".split(" ")
.map(name => element.addEventListener(name, handleEvent, false));
If you want to handle lots of events and have different requirements per listener you can also pass an object which most people tend to forget.
const el = document.querySelector("#myId");
const eventHandler = {
// called for each event on this element
handleEvent(evt) {
switch (evt.type) {
case "click":
case "touchstart":
// click and touchstart share click handler
this.handleClick(e);
break;
case "touchend":
this.handleTouchend(e);
break;
default:
this.handleDefault(e);
}
},
handleClick(e) {
// do something
},
handleTouchend(e) {
// do something different
},
handleDefault(e) {
console.log("unhandled event: %s", e.type);
}
}
el.addEventListener(eventHandler);
Update 05/2019:
const el = document.querySelector("#myId");
const eventHandler = {
handlers: {
click(e) {
// do something
},
touchend(e) {
// do something different
},
default(e) {
console.log("unhandled event: %s", e.type);
}
},
// called for each event on this element
handleEvent(evt) {
switch (evt.type) {
case "click":
case "touchstart":
// click and touchstart share click handler
this.handlers.click(e);
break;
case "touchend":
this.handlers.touchend(e);
break;
default:
this.handlers.default(e);
}
}
}
Object.keys(eventHandler.handlers)
.map(eventName => el.addEventListener(eventName, eventHandler))
Unless your do_something function actually does something with any given arguments, you can just pass it as the event handler.
var first = document.getElementById('first');
first.addEventListener('touchstart', do_something, false);
first.addEventListener('click', do_something, false);
Simplest solution for me was passing the code into a separate function and then calling that function in an event listener, works like a charm.
function somefunction() { ..code goes here ..}
variable.addEventListener('keyup', function() {
somefunction(); // calling function on keyup event
})
variable.addEventListener('keydown', function() {
somefunction(); //calling function on keydown event
})
I have a small solution that attaches to the prototype
EventTarget.prototype.addEventListeners = function(type, listener, options,extra) {
let arr = type;
if(typeof type == 'string'){
let sp = type.split(/[\s,;]+/);
arr = sp;
}
for(let a of arr){
this.addEventListener(a,listener,options,extra);
}
};
Allows you to give it a string or Array. The string can be separated with a space(' '), a comma(',') OR a Semicolon(';')
I just made this function (intentionally minified):
((i,e,f)=>e.forEach(o=>i.addEventListener(o,f)))(element, events, handler)
Usage:
((i,e,f)=>e.forEach(o=>i.addEventListener(o,f)))(element, ['click', 'touchstart'], (event) => {
// function body
});
The difference compared to other approaches is that the handling function is defined only once and then passed to every addEventListener.
EDIT:
Adding a non-minified version to make it more comprehensible. The minified version was meant just to be copy-pasted and used.
((element, event_names, handler) => {
event_names.forEach( (event_name) => {
element.addEventListener(event_name, handler)
})
})(element, ['click', 'touchstart'], (event) => {
// function body
});
I'm new at JavaScript coding, so forgive me if I'm wrong.
I think you can create an object and the event handlers like this:
const myEvents = {
click: clickOnce,
dblclick: clickTwice,
};
function clickOnce() {
console.log("Once");
}
function clickTwice() {
console.log("Twice");
}
Object.keys(myEvents).forEach((key) => {
const myButton = document.querySelector(".myButton")
myButton.addEventListener(key, myEvents[key]);
});
<h1 class="myButton">Button</h1>
And then click on the element.
document.getElementById('first').addEventListener('touchstart',myFunction);
document.getElementById('first').addEventListener('click',myFunction);
function myFunction(e){
e.preventDefault();e.stopPropagation()
do_something();
}
You should be using e.stopPropagation() because if not, your function will fired twice on mobile
This is my solution in which I deal with multiple events in my workflow.
let h2 = document.querySelector("h2");
function addMultipleEvents(eventsArray, targetElem, handler) {
eventsArray.map(function(event) {
targetElem.addEventListener(event, handler, false);
}
);
}
let counter = 0;
function countP() {
counter++;
h2.innerHTML = counter;
}
// magic starts over here...
addMultipleEvents(['click', 'mouseleave', 'mouseenter'], h2, countP);
<h1>MULTI EVENTS DEMO - If you click, move away or enter the mouse on the number, it counts...</h1>
<h2 style="text-align:center; font: bold 3em comic; cursor: pointer">0</h2>
What about something like this:
['focusout','keydown'].forEach( function(evt) {
self.slave.addEventListener(evt, function(event) {
// Here `this` is for the slave, i.e. `self.slave`
if ((event.type === 'keydown' && event.which === 27) || event.type === 'focusout') {
this.style.display = 'none';
this.parentNode.querySelector('.master').style.display = '';
this.parentNode.querySelector('.master').value = this.value;
console.log('out');
}
}, false);
});
// The above is replacement of:
/* self.slave.addEventListener("focusout", function(event) { })
self.slave.addEventListener("keydown", function(event) {
if (event.which === 27) { // Esc
}
})
*/
You can simply do it iterating an Object. This can work with a single or multiple elements. This is an example:
const ELEMENTS = {'click': element1, ...};
for (const [key, value] of Object.entries(ELEMENTS)) {
value.addEventListener(key, () => {
do_something();
});
}
When key is the type of event and value is the element when you are adding the event, so you can edit ELEMENTS adding your elements and the type of event.
Semi-related, but this is for initializing one unique event listener specific per element.
You can use the slider to show the values in realtime, or check the console.
On the <input> element I have a attr tag called data-whatever, so you can customize that data if you want to.
sliders = document.querySelectorAll("input");
sliders.forEach(item=> {
item.addEventListener('input', (e) => {
console.log(`${item.getAttribute("data-whatever")} is this value: ${e.target.value}`);
item.nextElementSibling.textContent = e.target.value;
});
})
.wrapper {
display: flex;
}
span {
padding-right: 30px;
margin-left: 5px;
}
* {
font-size: 12px
}
<div class="wrapper">
<input type="range" min="1" data-whatever="size" max="800" value="50" id="sliderSize">
<em>50</em>
<span>Size</span>
<br>
<input type="range" min="1" data-whatever="OriginY" max="800" value="50" id="sliderOriginY">
<em>50</em>
<span>OriginY</span>
<br>
<input type="range" min="1" data-whatever="OriginX" max="800" value="50" id="sliderOriginX">
<em>50</em>
<span>OriginX</span>
</div>
//catch volume update
var volEvents = "change,input";
var volEventsArr = volEvents.split(",");
for(var i = 0;i<volknob.length;i++) {
for(var k=0;k<volEventsArr.length;k++) {
volknob[i].addEventListener(volEventsArr[k], function() {
var cfa = document.getElementsByClassName('watch_televised');
for (var j = 0; j<cfa.length; j++) {
cfa[j].volume = this.value / 100;
}
});
}
}
'onclick' in the html works for both touch and click event. Here's the example.
This mini javascript libary (1.3 KB) can do all these things
https://github.com/Norair1997/norjs/
nor.event(["#first"], ["touchstart", "click"], [doSomething, doSomething]);

Categories

Resources