Get the name (type) of the event that was fired (triggered)

JavascriptJqueryEventsDom

Javascript Problem Overview


I have the following code:

$('#button').on('click change', function() {
    alert('Who fired me, click or change?');
});

How can I know if the event called was "click" or "change"?

Javascript Solutions


Solution 1 - Javascript

event.type will get you what you want.

DEMO

See also: List of event types

$('#button').on('click change', function(){
    console.log(event.type + ' is fired');
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="text" id="tipo-imovel" />

Solution 2 - Javascript

@Vega solution is correct for simple events. However, if you namespace your events, (i.e. player.play) then you must get the namespace as well. For example, lets say I trigger the event:

$('#myElement').trigger('player.play');

Then to get the full event name, you need to do the following:

$('#myElement').on('player.play', function(e) {
    console.log('Full event name: ' + e.type + '.' + e.namespace);
});

Solution 3 - Javascript

For listening to events fired the below snippet can be used:

     $(document).on("abort activate afterprint beforeactivate beforecopy beforecut beforedeactivate beforepaste beforeprint beforeunload blur bounce change CheckboxStateChange click contextmenu copy cut dblclick deactivate deactivate DOMAttrModified DOMCharacterDataModified DOMFocusIn DOMFocusOut DOMMouseScroll DOMNodeInserted DOMNodeInsertedIntoDocument DOMNodeRemoved DOMNodeRemovedFromDocument DOMSubtreeModified drag dragdrop dragend dragenter dragexit draggesture dragleave dragover dragstart drop error error (window) finish focus focusin focusout hashchange help input keydown keypress keyup load message mousedown mouseenter mouseleave mousemove mouseout mouseover mouseup mousewheel offline online overflow overflowchanged paste RadioStateChange readystatechange readystatechange (XMLDocument) readystatechange (XMLHttpRequest) reset resize scroll search select selectionchange selectstart start stop submit textInput underflow unload ",function(e){
      console.log(e.type);
    });

It is a little bit lengthy but surely will be helpful.:)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMarcio MazzucatoView Question on Stackoverflow
Solution 1 - JavascriptSelvakumar ArumugamView Answer on Stackoverflow
Solution 2 - JavascriptTroy GrosfieldView Answer on Stackoverflow
Solution 3 - JavascriptAryeshView Answer on Stackoverflow