Search code examples
javascriptinputonbluronfocus

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?


Solution

  • 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'