Just like the question states. I want to fire off an event that calls a method everytime the user clicks on the web page.
How do I do that without use of jQuery?
Without using jQuery, I think you could do it like this:
if (document.addEventListener) {
document.addEventListener('click',
function (event) {
// handle event here
},
false
);
} else if (document.attachEvent) {
document.attachEvent('onclick',
function (event) {
// handle event here
}
);
}
Here's one way to do it..
if (window.addEventListener)
{
window.addEventListener('click', function (evt)
{
//do something
}, false);
}
else if(window.attachEvent)
{
window.attachEvent('onclick', function (evt)
{
// do something (for IE)
});
}
$(document).click(function(){});
document.onclick = function() { alert("hello"); };
note that this will only allow for one such function though.
Related
I'm trying to remove an event listener inside of a listener definition:
canvas.addEventListener('click', function(event) {
click++;
if(click == 50) {
// remove this event listener here!
}
// More code here ...
How could I do that? this = event...
You need to use named functions.
Also, the click variable needs to be outside the handler to increment.
var click_count = 0;
function myClick(event) {
click_count++;
if(click_count == 50) {
// to remove
canvas.removeEventListener('click', myClick);
}
}
// to add
canvas.addEventListener('click', myClick);
EDIT: You could close around the click_counter variable like this:
var myClick = (function( click_count ) {
var handler = function(event) {
click_count++;
if(click_count == 50) {
// to remove
canvas.removeEventListener('click', handler);
}
};
return handler;
})( 0 );
// to add
canvas.addEventListener('click', myClick);
This way you can increment the counter across several elements.
If you don't want that, and want each one to have its own counter, then do this:
var myClick = function( click_count ) {
var handler = function(event) {
click_count++;
if(click_count == 50) {
// to remove
canvas.removeEventListener('click', handler);
}
};
return handler;
};
// to add
canvas.addEventListener('click', myClick( 0 ));
EDIT: I had forgotten to name the handler being returned in the last two versions. Fixed.
canvas.addEventListener('click', function(event) {
click++;
if(click == 50) {
this.removeEventListener('click',arguments.callee,false);
}
Should do it.
You could use a named function expression (in this case the function is named abc), like so:
let click = 0;
canvas.addEventListener('click', function abc(event) {
click++;
if (click >= 50) {
// remove event listener function `abc`
canvas.removeEventListener('click', abc);
}
// More code here ...
}
Quick and dirty working example: http://jsfiddle.net/8qvdmLz5/2/.
More information about named function expressions: http://kangax.github.io/nfe/.
If #Cybernate's solution doesn't work, try breaking the trigger off in to it's own function so you can reference it.
clickHandler = function(event){
if (click++ == 49)
canvas.removeEventListener('click',clickHandler);
}
canvas.addEventListener('click',clickHandler);
element.querySelector('.addDoor').onEvent('click', function (e) { });
element.querySelector('.addDoor').removeListeners();
HTMLElement.prototype.onEvent = function (eventType, callBack, useCapture) {
this.addEventListener(eventType, callBack, useCapture);
if (!this.myListeners) {
this.myListeners = [];
};
this.myListeners.push({ eType: eventType, callBack: callBack });
return this;
};
HTMLElement.prototype.removeListeners = function () {
if (this.myListeners) {
for (var i = 0; i < this.myListeners.length; i++) {
this.removeEventListener(this.myListeners[i].eType, this.myListeners[i].callBack);
};
delete this.myListeners;
};
};
It looks like no one's covered the part of the current JavaScript DOM specification that gives you a mechanism to remove your event listener without using removeEventListener. If we look at https://dom.spec.whatwg.org/#concept-event-listener we see that there are a number of properties that can be passed to control event listening:
{
type (a string)
callback (null or an EventListener object)
capture (a boolean, initially false)
passive (a boolean, initially false)
once (a boolean, initially false)
signal (null or an AbortSignal object)
removed (a boolean for bookkeeping purposes, initially false)
}
Now, there's a lot of useful properties in that list, but for the purposes of removing an event listener it's the signal property that we want to make use of (which was added to the DOM level 3 in late 2020), because it lets us tell the JS engine to remove an event listener by just calling abort() instead of having to bother with removeEventListener:
const canvasListener = (new AbortController()).signal;
canvas.addEventListener('click', () => {
click++;
if (click === 50) {
canvasListener.abort();
} else {
doSomethingWith(click);
}
}, {
signal: canvasListener
});
(Note that this does not use the useCapture flag, because the useCapture flag is essentially completely useless)
And done: the JS engine will abort and clean up our event listener. No keeping a reference to the handling function, no making sure we call removeEventListener with the exact same properties as we called addEventListener: we just cancel the listener.
I think you may need to define the handler function ahead of time, like so:
var myHandler = function(event) {
click++;
if(click == 50) {
this.removeEventListener('click', myHandler);
}
}
canvas.addEventListener('click', myHandler);
This will allow you to remove the handler by name from within itself.
If someone uses jquery, he can do it like this :
var click_count = 0;
$( "canvas" ).bind( "click", function( event ) {
//do whatever you want
click_count++;
if ( click_count == 50 ) {
//remove the event
$( this ).unbind( event );
}
});
Hope that it can help someone.
Note that the answer given by #user113716 work nicely :)
A way to achieve that is use jquery, so you can use:
canvas.click(yourfunction);
then you can detach all event listener with:
canvas.off();
Try this, it worked for me.
<button id="btn">Click</button>
<script>
console.log(btn)
let f;
btn.addEventListener('click', f=function(event) {
console.log('Click')
console.log(f)
this.removeEventListener('click',f)
console.log('Event removed')
})
</script>
I'm trying to remove an event listener inside of a listener definition:
canvas.addEventListener('click', function(event) {
click++;
if(click == 50) {
// remove this event listener here!
}
// More code here ...
How could I do that? this = event...
You need to use named functions.
Also, the click variable needs to be outside the handler to increment.
var click_count = 0;
function myClick(event) {
click_count++;
if(click_count == 50) {
// to remove
canvas.removeEventListener('click', myClick);
}
}
// to add
canvas.addEventListener('click', myClick);
EDIT: You could close around the click_counter variable like this:
var myClick = (function( click_count ) {
var handler = function(event) {
click_count++;
if(click_count == 50) {
// to remove
canvas.removeEventListener('click', handler);
}
};
return handler;
})( 0 );
// to add
canvas.addEventListener('click', myClick);
This way you can increment the counter across several elements.
If you don't want that, and want each one to have its own counter, then do this:
var myClick = function( click_count ) {
var handler = function(event) {
click_count++;
if(click_count == 50) {
// to remove
canvas.removeEventListener('click', handler);
}
};
return handler;
};
// to add
canvas.addEventListener('click', myClick( 0 ));
EDIT: I had forgotten to name the handler being returned in the last two versions. Fixed.
canvas.addEventListener('click', function(event) {
click++;
if(click == 50) {
this.removeEventListener('click',arguments.callee,false);
}
Should do it.
You could use a named function expression (in this case the function is named abc), like so:
let click = 0;
canvas.addEventListener('click', function abc(event) {
click++;
if (click >= 50) {
// remove event listener function `abc`
canvas.removeEventListener('click', abc);
}
// More code here ...
}
Quick and dirty working example: http://jsfiddle.net/8qvdmLz5/2/.
More information about named function expressions: http://kangax.github.io/nfe/.
If #Cybernate's solution doesn't work, try breaking the trigger off in to it's own function so you can reference it.
clickHandler = function(event){
if (click++ == 49)
canvas.removeEventListener('click',clickHandler);
}
canvas.addEventListener('click',clickHandler);
element.querySelector('.addDoor').onEvent('click', function (e) { });
element.querySelector('.addDoor').removeListeners();
HTMLElement.prototype.onEvent = function (eventType, callBack, useCapture) {
this.addEventListener(eventType, callBack, useCapture);
if (!this.myListeners) {
this.myListeners = [];
};
this.myListeners.push({ eType: eventType, callBack: callBack });
return this;
};
HTMLElement.prototype.removeListeners = function () {
if (this.myListeners) {
for (var i = 0; i < this.myListeners.length; i++) {
this.removeEventListener(this.myListeners[i].eType, this.myListeners[i].callBack);
};
delete this.myListeners;
};
};
It looks like no one's covered the part of the current JavaScript DOM specification that gives you a mechanism to remove your event listener without using removeEventListener. If we look at https://dom.spec.whatwg.org/#concept-event-listener we see that there are a number of properties that can be passed to control event listening:
{
type (a string)
callback (null or an EventListener object)
capture (a boolean, initially false)
passive (a boolean, initially false)
once (a boolean, initially false)
signal (null or an AbortSignal object)
removed (a boolean for bookkeeping purposes, initially false)
}
Now, there's a lot of useful properties in that list, but for the purposes of removing an event listener it's the signal property that we want to make use of (which was added to the DOM level 3 in late 2020), because it lets us tell the JS engine to remove an event listener by just calling abort() instead of having to bother with removeEventListener:
const canvasListener = (new AbortController()).signal;
canvas.addEventListener('click', () => {
click++;
if (click === 50) {
canvasListener.abort();
} else {
doSomethingWith(click);
}
}, {
signal: canvasListener
});
(Note that this does not use the useCapture flag, because the useCapture flag is essentially completely useless)
And done: the JS engine will abort and clean up our event listener. No keeping a reference to the handling function, no making sure we call removeEventListener with the exact same properties as we called addEventListener: we just cancel the listener.
I think you may need to define the handler function ahead of time, like so:
var myHandler = function(event) {
click++;
if(click == 50) {
this.removeEventListener('click', myHandler);
}
}
canvas.addEventListener('click', myHandler);
This will allow you to remove the handler by name from within itself.
If someone uses jquery, he can do it like this :
var click_count = 0;
$( "canvas" ).bind( "click", function( event ) {
//do whatever you want
click_count++;
if ( click_count == 50 ) {
//remove the event
$( this ).unbind( event );
}
});
Hope that it can help someone.
Note that the answer given by #user113716 work nicely :)
A way to achieve that is use jquery, so you can use:
canvas.click(yourfunction);
then you can detach all event listener with:
canvas.off();
Try this, it worked for me.
<button id="btn">Click</button>
<script>
console.log(btn)
let f;
btn.addEventListener('click', f=function(event) {
console.log('Click')
console.log(f)
this.removeEventListener('click',f)
console.log('Event removed')
})
</script>
I have a click event as follow which works fine:
$('#showmenu').off('click').on('click', function(e) {
e.preventDefault();
e.stopPropagation();
show_menu();
return false;
});
where show_menu is:
function show_menu(e) {
if (!collapseForm.is(':visible')) {
collapseForm.show();
showMenu.removeClass(chevronDown).addClass(checvronUp);
searchAgain.hide();
} else {
collapseForm.hide();
showMenu.removeClass(checvronUp).addClass(checvronDown);
searchAgain.show();
}
}
I would like to be able to do something like that:
$('#showmenu').off('click').on('click', show_menu(e));
Is it possible to pass "e" to the callback function by doing the following?
function show_menu(e) {
e.preventDefault();
e.stopPropagation();
if (!collapseForm.is(':visible')) {
collapseForm.show();
showMenu.removeClass(chevronDown).addClass(checvronUp);
searchAgain.hide();
} else {
collapseForm.hide();
showMenu.removeClass(checvronUp).addClass(chevronDown);
searchAgain.show();
}
return false;
}
The event object is passed to the function when the function is called (by the event firing).
You have to pass the function to the on method.
$('#showmenu').off('click').on('click', show_menu);
I have Jquery click event and i want to prevent multiple click before executing my function UpdateItemStatus(this.id);, so i have tried below code using on/off event,
$('#tableItems').on('click', 'tr', function (e) {
if ($(e.target).closest("td").hasClass("cssClick")) {
$(this).off(e);
UpdateItemStatus(this.id);
$(this).on(e);
}
});
but how do i turn .on? as it's not working, not able to click again.
How about having a global variable which decides the button click action?
Something like this?
var clickevent = true;
$('#tableItems').on('click', 'tr', function (e) {
if(clickevent){
if ($(e.target).closest("td").hasClass("cssClick")) {
clickevent = false;
UpdateItemStatus(this.id);
clickevent = true;
}
}
});
if UpdateItemStatus function has ajax then i recommend you to put clickevent = true inside success of that ajax
You don't need to use off() for your code. Use return false:
$('#tableItems').on('click', 'tr', function (e) {
if ($(e.target).closest("td").hasClass("cssClick")) {
return false;
} else{
//do stuff here
}
});
I would probably use something like this :
var inputstate = false;
$('#tableItems').on('click', 'tr', function (e) {
if ($(e.target).closest("td").hasClass("cssClick")) {
if(!inputstate){
inputstate = true;
setTimeout((function(element){
return function(){
UpdateItemStatus(element);
inputstate = false;
};
})(this),50);
}
}
});
the setTimeout used to "defer the call" of your UpdateItemStatus function.
Because if this listener is fired, (an other listener cannot be fired at the same time) the value of the boolean will change to the end state before that the next click will be handled
Seems like your UpdateItemStatus() uses some asynchronous call (ajax?), so here's how i would do it:
$('#tableItems').on('click', 'tr', function (e) {
var $td = $(e.target).closest("td");
if ($td.hasClass("cssClick")) {
$td.toggleClass("cssClick");
UpdateItemStatus(this.id).done(function(){
$td.toggleClass("cssClick");
});
}
});
and in UpdateItemStatus:
function UpdateItemStatus(id){
//do stuff
return $.ajax(...);
}
I have some simple code, but currently it does not remove the listener after the first call. How can I achieve this? Or do I really need to add redundant if/else checks on a var set upon notice?
document.addEventListener("contextmenu", function(e){
alert("Please remember this is someone's art! Give credit where it is deserved!");
document.removeEventListener("contextmenu", function(e){
console.log('User has been warned...');
});
}, false);
Updated code Still same message every right click
document.addEventListener("contextmenu", function msg(e){
alert("Please remember this is someone's art! Give credit where it is deserved!");
e.removeEventListener("contextmenu", msg, false);
}, false);
you need to pass the same function to remove as add.
the easy way to do that is to give the function a name and pass the name to removeEventListener():
document.addEventListener("contextmenu", function me(e){
alert("Please remember this is someone's art! Give credit where it is deserved!");
document.removeEventListener("contextmenu", me, false);
}, false);
see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.removeEventListener for a good overview
obligatory fiddle: http://jsfiddle.net/w1kzLkoL/
tested in chrome, firefox, and IE10
You may try this example:
document.addEventListener("contextmenu", (function() {
var done = false;
return function(e) {
if (!done) {
done = true;
alert('Warning !');
}
console.log('done ...', done);
e.preventDefault();
return false;
};
})(), false);
Open console... right click
Easiest way is to just configure the event listener with { once: true }.
document.addEventListener('contextmenu', (e) => {
your code...
}, { once: true });