Search code examples
javascriptinternet-explorerdom-events

focusin event triggers in IE for floated and Inline Block element


The focusin event which is a part of form inputs and link tag, is getting applied for div and span tags. It happens for floated and inline-block element. The issue is spotted in IE (8 and 9).

Demo ==> http://jsfiddle.net/Agczq/

Is there a way to stop this?


Solution

  • Unlike you might expect focusin and focusout do bubble up, unlike the regular focus event. The two main ways of dealing with this are: Event delegation, or simply stopping the event from bubbling up.

    Your fiddle is hard to make sense of (ie: don't know what you're trying to do). The first thing that comes to mind (after moving your JS code to the JavaScript field on jsfiddle) is that you're capturing a focus event in good browsers, and the bubbling focusin in crummy IE.
    This can be quite annoying, particularly since IE doesn't support actual event capturing. Nevertheless, here's a (simple, but tested and working) suggestion:

    function mycb(evt)
    {
        evt = evt || window.event;//get event object
        var from = evt.target || evt.srcElement;//get source
        if (evt.stopPropagation)//stop event from bubbling
        {
            evt.stopPropagation();//shouldn't be necessary, but you never know
        }
        else
        {
            evt.cancelBubble = true;//stop propagation in IE-lingo
        }
        if (from.tagName === 'DIV' || from.tagName === 'SPAN')
        {//if source was a tag that souldn't fire event, return false;
            if (evt.preventDefault)
            {
                evt.preventDefault();
                return false;
            }
            evt.returnValue = false;
            return false;
        }
         alert("fired!!!");
    }
    
    var elem = document.getElementById("mybox");
    if( elem.attachEvent )
    {
        elem.attachEvent("onfocusin",  mycb);
    }
    else
    {
        elem.addEventListener("focus", mycb, true);
    }
    

    This code was tested in IE8, fiddle can be found here.
    It just so happens I read about this event today, here. A source worth mentioning, I reckon.

    Hope this helps