How to determine which HTML element and/or which event called a function?

Asked

Viewed 2,787 times

13

I have a function called by two different HTML elements and each element calls the function through a given event.

$("#tempoInicial").on("blur", manipulaTempoFinal);
$("#operadorTempo").on("change", manipulaTempoFinal);

function manipulaTempoFinal() {
    var tempoInicial = $("#tempoInicial");
    var operador = $("#operadorTempo");
    if (operador.val() == "4" && tempoInicial.val() != "") {
        tempoFinal.removeAttr("disabled");
        $("#tempoInicial, #operadorTempo").rules("remove", "skip_or_fill_minimum");
        $("#tempoInicial, #operadorTempo, #tempoFinal").rules("add", {
            require_from_group: [3, ".temposOperadorWeb"],
            messages: {
                require_from_group: "Ao entrar com tempo inicial e escolher o operador \"Entre\" o campo tempo final passa a ser obrigatório."
            }
        });
    } else {
        tempoFinal.attr("disabled", "disabled");
        tempoFinal.val("");
        $("#tempoInicial, #operadorTempo, #tempoFinal").rules("remove", "require_from_group");
        $("#tempoInicial, #operadorTempo").rules("add", {
            skip_or_fill_minimum: [2, ".temposOperadorWeb"],
            messages: {
                skip_or_fill_minimum: "Ao preencher o tempo inicial selecione o operador ou vice-versa."
            }
        });
    }
}

Is there any way in the function manipulaTempoFinal I identify who called it and/or what event?

2 answers

9


The listeners jQuery event parameter takes a parameter with reference to an object representing the event. This object has attributes type and target, which contains the event type and the element that originally received the action, respectively.

In addition, within the function, the object represented by this refers to the element that is treating the event, not necessarily the same where the event occurred, but may be one of its descendants.

Example:

function manipulador(e) {
    console.log('evento: ' + e.type);
    console.log('componente: ' + e.target);
}

$('input, select')
    .on('change', manipulador)
    .on('blur', manipulador);

Demo at Jsfiddle

However, look at this other example:

<div>
<input/>
<select>
    <option>A</option>
    <option>B</option>
</select>
<div>
function manipulador(e) {
    console.log('evento: ' + e.type);
    console.log('componente: ' + e.target);
    console.log('componente: ' + this)
}

$('div')
    .on('change', manipulador)
    .on('blur', manipulador);

In this last example, the result in the console for an event change would be:

event: change

component: [Object Htmlinputelement]

component: [Object Htmldivelement]

Note that target returned the input that received the event, while this returned the div that treats the event.

Demo at Jsfiddle

  • Excellent answer! Added enough to know this information. Just one question, the way you did you add both to the change and to the selects and inputs Blur the function, correct?

  • @Philippegioseffi Correto!

  • 1

    @Philippegioseffi Note that I updated the response with some nuances about event.target and this.

  • 1

    It improved even more even the answer, ie using this could not always solve my problem depending on how it was called. Thank you even for the knowledge!

  • +1, much clearer. =)

5

The keyword this will always have the reference to the element that triggered the event.

So if within your function you call $(this) You will get the reference with a jQuery envelope.

Have a good post in the OS in this regard. Original text:

In jQuery, by default, this refers to the DOM element (not a jQuery Object) which Triggered an Event. In the [code snippet above], it is still the same DOM element, only it is Wrapped in a jQuery element by wrapping $() Around it. As with any argument to the jQuery constructor, Passing this into the constructor Transforms it into a jQuery Object.

Translating:

In jQuery, by default, the keyword this refers to the DOM element (not a jQuery object) that triggered an event. In the [code snippet above], it is still the same DOM element, only it is wrapped in a jQuery element by owning $() around it. As with any argument for a jQuery constructor, passing this to the constructor transforms it into a jQuery object.

In case you wanted to know which event was triggered, you can do it indirectly by passing an alias in the event call. Example:

$("#tempoInicial").on("blur", function(e) { manipulaTempoFinal('blur'); });

And the signature of your function can look like this:

function manipulaTempoFinal(pEvento)
[...]
  • Exactly what I needed. Just to complement, you would know to say the event?

  • Not directly, but you can pass an operation alias in the function call. I will edit the answer to add this part. [Edit] Okay, @Philippegioseffi. I hope it works for you!

  • 1

    Just an addendum, I don’t think you can pass parameters to functions the way you did, look at the question: How to pass parameters in function calls by reference in Javascript?.

  • Correct. Updated. I need coffee. =)

  • Anyway, thanks for your help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.