House3272 February 2016

Javascript, anyway to do a 'whileFocused' eventListener? (No JQuery)

Is there a way to implement or simulate a 'while focused' bind on a dom element? Say log a message every second, starting when onfocus occurs, but stops upon leaving.

Considering this:

myinput.addEventListener("focus", function(){
    setInterval(function(){
        console.log('Mouse on:' + this)
    }, 1000);
});

the only thing I can think of was using a global variable like:

var isfocused = false;
myinput.addEventListener("focus", function(){
    isfocused = true;
    setInterval(function(){
        if (isfocused)
            console.log('Mouse on:' + this)
    }, 1000);
});

then adding another listener for onblur to toggle 'isfocused'

But that feels.....just wrong. And plus the setInterval would continue firing off in the background right?

Answers


Scott Schwalbe February 2016

window.setInterval returns an id for your interval callback. You can then pass in that id to window.clearInterval(id) to stop it. Something like

var intervalId;
myinput.addEventListener("focus", function(){
    intervalId = setInterval(function(){
        console.log('Mouse on:' + this)
    }, 1000);
});
myinput.addEventListener("unfocus", function(){
    clearInterval(intervalId);
});


Dave Bush February 2016

Slight improvement to @Scott Schwalbe

(function(){
    var intervalId;
    myinput.addEventListener("focus", function(){
        intervalId = setInterval(function(){
            console.log('Mouse on:' + this)
        }, 1000);
    });
    myinput.addEventListener("blur", function(){
        clearInterval(intervalId); 
    });
})();

1) Wrap it in Immediately Invoked Function Expression to keep the global variable space pure.

2) The 'unfocus' event is really 'blur'

Post Status

Asked in February 2016
Viewed 3,275 times
Voted 6
Answered 2 times

Search




Leave an answer