简体   繁体   中英

Add/Remove CSS class on search input with jQuery

I have a search field and I have it so that when you click on the search icon, a class is added with a grey underline. My problem is that I cannot remove the class when I click outside of the search field.

Does anyone know how I can get the grey-line class to be removed when a user clicks outside the search field?

There is a lot going on so here is my javascript that handles this:

 //Header Search Handler function headerSearchHandler() { var $searchInput = $(".header-search input[type=text]"), $searchSubmit = $(".header-search input[type=submit]"), $mobSearchBtn = $(".mobile-search-btn"), $myAccountText = $(".menu-utility-user .account-text"), $miniCart = $("#header #mini-cart"), $searchForm = $(".header-search form"), $headerPromo = $(".header-promo-area"); // $mobSearchBtn.on("click touchend", function(e) { $(this).hide(); //$myAccountText.hide(); $searchInput.show(); $searchInput.addClass('grey-line'); $searchSubmit.show(); $miniCart.addClass("search-open"); $searchForm.addClass("search-open"); setTimeout(function() { $searchInput.addClass("active").focus(); }, 500); e.stopPropogation(); }); $searchInput.on("click touchend", function(e) { $searchInput.addClass('grey-line'); e.stopPropogation(); }).blur(function(e) { var $this = $(this); if ($this.hasClass("active")) { $this.removeClass("active"); $searchSubmit.hide(); $mobSearchBtn.show(); $miniCart.removeClass("search-open"); $searchForm.removeClass("search-open"); } }); $('body').on("click", function(e) { if ($searchInput.hasClass('grey-line')) { $searchInput.removeClass('grey-line'); e.stopPropogation(); } }); } //End Header Search Handler 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <form id="search" role="search" onsubmit="return checkForm()" action="${searchPage}" method="get" name="simpleSearch"> <fieldset> <legend aria-hidden="true" class="visually-hidden">${Resource.msg('simplesearch.searchCatalog', 'search', null)}</legend> <button class="mobile-search-btn" for="q" aria-hidden="false" aria-expanded="false" aria-controls="q" tabindex="0" aria-label="show search field button tap twice to open search input field">${Resource.msg('simplesearch.searchlabel', 'search', null)}</button> <input tabindex="0" type="text" id="q" name="q" value="" class="searchField" placeholder="${Resource.msg('simplesearch.searchtext', 'search', null)}" style="font-style:normal;" unbxdattr="sq" /> <input tabindex="0" type="submit" name="go" value="${Resource.msg('simplesearch.searchtext', 'search', null)}" unbxdattr="sq_bt" /> </fieldset> </form> 

Try using blur .

$('.searchFieldClass').blur(function() {
   $(this).removeClass('.greyLineClass');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM