Reputation: 653
How can I tell if a function being called originated from a click event?
For instance, an anchor or button is clicked and the event is captured and a function is called.
Inside of this function in firebug's stack trace I can see an Object like this
Object { originalEvent=Event click, type="click", timeStamp=97128874, more...}
It says the originalEvent came from a click.
Depending on whether it came from or click or not, processing occurs differently.
Is there a way to tell if the function being called originated from a click event?
Upvotes: 3
Views: 4901
Reputation: 7810
Any function that is triggered with an event is sent an event object. Call .type
on this object and it will return which event it is. Here is a simple example from the jQuery docs:
$( "a" ).click(function( event ) {
alert( event.type ); // "click"
});
So lets say you want to listen for both clicks and typing in a text input:
$( "input" ).on("click keyup", eventHandler);
But you want to do something special on a click:
eventHandler = function(event){
if (event.type === 'click'){
// code to execute if there is a click
} else {
// code to execute if there is a non-click event
}
// code to execute for both click and non-click events
};
Upvotes: 5
Reputation: 74420
See it:
$('div').click(test);
function test(e){
if(e && e.type === 'click')
alert('called from click!');
else alert('NOT called from click!');
}
test();
Upvotes: 4
Reputation: 206048
function myFn( evt ){
console.log( evt.type );
}
$('div').on('click mouseenter mouseleave', myFn);
Upvotes: 0
Reputation: 318182
That would be the event.type
var elem = document.getElementById('test');
elem.addEventListener('click', function(event) {
console.log(event.type)
}, false);
or in jQuery
$('#test').on('click paste mouseenter', function(event) {
console.log(event.type)
});
Upvotes: 4