Question

I need to be able to control when the blur event is actually triggered.

<div class="selectedcomp"></div>
<input type="text" class="textbox" maxlength="50" id="searchfavs" />
<div id="globalcompanyresultscontainer">
    <div id="globalcompanyresults">
    </div>
</div>

When a user is typing a query in #searchfavs I'm loading the results into #globalcompanyresults. When a user clicks a loaded result I copy the HTML of that result into another element:

$('#globalcompanyresults').on('click', 'div.company-card img', function () {
    $('#globalcompanyresults').html('');
    $('.selectedcomp').html($(this).parent()[0].outerHTML);
});  

As soon as the user clicks outside the #searchfavs element or presses the tab key, also causing #searchfavs to loose focus, I want to clear all results, simply by calling this:

    $("#searchfavs").blur(function () {
        $('#globalcompanyresults').html('');
    });

However, this function is also called as soon as the user clicks a result in #globalcompanyresults, the blur event is thrown, causing #globalcompanyresults to be empty and I cannot access the clicked result HTML anymore.

onblur, may NOT be triggered if a result in #globalcompanyresults is clicked, by a click elsewhere or by pressing the tab key it's all good.

Était-ce utile?

La solution

If you only want to perform the logic when the tab key is pressed, why not respond to something like the keydown event instead of the blur event?

$('#searchfavs').keydown(function(e) { 
    if (e.keyCode == 9) {
        $('#globalcompanyresults').html('');
    }
});
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top