Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable jQuery blur event on certain selector

I have the following jQuery and HTML which hide the search result when the focus on the input has been lost.

This code hides my div with id #searchResult when the elements on #searchResult are clicked. I want to disable blur when elements on #searchResult div are clicked. Basically, I want to hide <div id="searchResult"> when the focus is lost and show when it's on focus. How can I achieve that?

$(document).on("blur", "#txtSearchTerm", function () {
    $('#searchResult').hide();
});

$(document).on("focus", "#txtSearchTerm", function () {
    $('#searchResult').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="txtSearchTerm" type="text">

<div id="searchResult">
    <ul>
        <li>
            <a href="http://www.google.com">
                <div class="title">Google.com</div>
                <div class="content">Click here</div>
            </a>
        </li>
        <li>
            <a href="http://www.google.com">
               <div class="title">Google.com</div>
               <div class="content">Click here</div>
           </a>
        </li>
    </ul>
</div>

<div id="searchResult"> will be hidden on every click of elements inside it.

like image 383
Kiran Shahi Avatar asked Oct 13 '17 11:10

Kiran Shahi


People also ask

How to stop blur event in jQuery?

Preventing the blur If you want to prevent the blur event from being fired, you have to do so when you are inside the mousedown event, you can do so by invoking the method preventDefault() on the event. Click the checkbox, focus input & then click the button, the textfield never loses focus now.

How do I cancel my blur event?

The blur event is not cancelable.

How to off event in jQuery?

jQuery unbind() MethodUse the off() method instead. The unbind() method removes event handlers from selected elements. This method can remove all or selected event handlers, or stop specified functions from running when the event occurs. This method can also unbind event handlers using an event object.

How to bind blur event in jQuery?

$( "#field1" ). blur(function() { alert( "Lose focus from Field1" ); }); Note : In jQuery blur( handler ) method is used to bind an event handler to the "blur" JavaScript event, or trigger that event on an element.


1 Answers

You can simply turn off your blur event with the following code.

$(document).off("blur", "#txtSearchTerm");
like image 177
Muhammad Jahanzeb Avatar answered Oct 23 '22 12:10

Muhammad Jahanzeb