Paul
Paul

Reputation: 1947

jQuery .has(":focus") in FF/Chrome/Safari

I have a textbox that has filter as you type results below it. I have jQuery that detects when focus leaves the textbox so it can hide the results div. BUT I don't want to hide the results if the results are click on so that I can use that click to redirect to a different page for that item.

I'm using .has(":focus") to check if my results div or any of its children have focus. My problem is that this only works in IE as far as I can tell. Anyone know why?

$("#TextBox").blur(function () {
    if ($("#ResultsDIV").has(":focus").length == 0) {  //if you click on anything other than the results
        $("#ResultsDIV").hide();  //hide the results
    }
});

UPDATE: Thanks to Climbage I've got this working...

var resultsSelected = false;
$("#ResultsDIV").hover(
    function () { resultsSelected = true; },
    function () { resultsSelected = false; }
);
$("#TextBox").blur(function () {
    if (!resultsSelected) {  //if you click on anything other than the results
        $("#ResultsDIV").hide();  //hide the results
    }
});

Working Example: http://jsfiddle.net/cB2CN/

Upvotes: 2

Views: 3384

Answers (1)

Mike Park
Mike Park

Reputation: 10931

The problem is that all not elements on the DOM actually accept focus, and it's up to the browser to decide which ones do. See Which HTML elements can receive focus?

Maybe have a hover event on your #ResultsDIV that sets a global variable to determine if the element has focus when you click on it.

Upvotes: 3

Related Questions