aborted
aborted

Reputation: 4541

Double event handler and one function. How to prevent executing code twice?

I have one callback function bound to two events (change and focusout). However, I need the focusout to happen only when the element we're interacting with is not a checkbox.

This is the example code:

$(document).on('focusout change', '.selector', function() {
    if ($(this).is(':checkbox')) {
        // Do stuff and prevent the focusout to trigger. HOW???
    }

    doStuff(); // Action that applies to both cases, but needs to be limited at one execution only
});

The code above will execute twice:

I tried using .off, but it ends up killing the focousout handler altogether, which I will need later for other elements which aren't checkboxes.

What would be the way to prevent the focusout handler to trigger for certain elements?

Upvotes: 0

Views: 2159

Answers (2)

Da Silva Ciril
Da Silva Ciril

Reputation: 1

The best way is to affect both events (or more) to the same function, like this :

A text input for example

<input id="myfield" type="text" />

Now the Javascript

var myfield = document.getElementById('myfield');

myfield.onfocus = myfield.onchange = function(e)
{
    //your code
}

Yo can even add an other element

button.onclick = myfield.onkeyup = function(e)
{
    //when the client press the enter key
    if(e.key && e.key == "Enter")
    {
        //catch the target
    }
    //when the client click the button
    else if(!e.key || e.target == button)
    {
        //catch the target
    }

    //otherwise you can do not care about the target and just execute your function
}

You must only know that you can add many elements and many events

element1.onfocus = element1.onblur = element2.onchange = element3.onchange = function(e){//your code}

Upvotes: 0

Jaromanda X
Jaromanda X

Reputation: 1

What you want to do is

$(document).on('focusout change', '.selector', function(event) {

event is an event object, which has properties, one of which is type. Checking the type you can now see if your function has been called because of a focusout or a change and run code as appropriate

Upvotes: 1

Related Questions