Jquery - Differentiate between 'click' and 'focus' on same input when using both

Rob Owl picture Rob Owl · Mar 13, 2014 · Viewed 8.2k times · Source

I'm trying to trigger an event on an input if the input is clicked or if the input comes in to focus.

The issue i'm having is preventing the event from firing twice on the click as, obviously, clicking on the input also puts it in focus. I've put a very loose version of this on jfiddle to show you what I mean, code as below:

HTML:

<body>
    <input type="textbox" name="tb1" class="input1"></input>
    <label> box 1 </label>
    <input type="textbox" name="tb2" class="input2"></input>
    <label> box 2 </label>
</body>

JQuery

$(function () {
    $('.input2').click(function() {
        alert("click");
    });
    $('.input2').focus(function() {
        alert("focus");
    });
});

JSFiddle: http://jsfiddle.net/XALSn/2/

You'll see that when you tab to input2 you get one alert, but if you click you get two. Ideally for my scenario, it needs to be one alert and ignore the other. it also doesn't seem to actually focus.

Thanks in advance for any advice.

Answer

Moob picture Moob · Mar 14, 2014

How about setting a flag on focus so we can fire on focus and ignore clicks but then listen for clicks on the focussed element too? Make sense? Take a look at the demo jsFiddle - If you focus or click on the unfocussed .index2 it triggers the focus event and ignores the click. Whilst in focus, clicking on it will trigger the click.

I have no idea why you would want this (I cant imagine anyone wanting to click on a focussed element for any reason (because the carat is already active in the field) but here you go:

$(function () {
    $('.input2').on("click focus blur", function(e) {
        e.stopPropagation();
        if(e.type=="click"){
            if($(this).data("justfocussed")){
                $(this).data("justfocussed",false);
            } else {
                //I have been clicked on whilst in focus
                console.log("click");
            }
        } else if(e.type=="focus"){
            //I have been focussed on (either by clicking on whilst blurred or by tabbing to)
            console.log("focus");
            $(this).data("justfocussed",true);
        } else {
            //I no longer have focus
            console.log("blur");
            $(this).data("justfocussed",false);
        }
    });
});

http://jsfiddle.net/XALSn/12/