Search code examples
javascriptjqueryonblur

Fire blur event unless specific element is clicked


I have three search categories (see first image). The user selects one and I show the search input that corresponds to that topic in the space of the categories (see second image). I automatically focus on the input with jQuery so the user can easily begin typing. If the user changes their mind and blurs the intput I hide it and again show the three categories.

This all works great if the user clicks enter to search, but I also want to allow them to be able to click the go button next to the search input field. The issue is that if they try to click the go button the input is blurred and then hidden and the submit click is never fired (I cannot unbind the blur event upon clicking this element because it is never fired - the blur is triggered first)

State 1:

state 2:

So is there any way to execute the function bound to the blur event (hiding the div) unless this "go" element is clicked using jQuery or JavaScript?


Solution

  • You have several options:

    1. You can only hide the input on blur if the focus has gone somewhere outside its container, so if the focus has gone to the "Go" button, you don't hide the input at all.

    2. You can your code design and fire the search question as an ajax call rather than a form submit.

    3. You can hide the input on blur after a brief setTimeout() which gives the form submission a chance to get sent before it's hidden.