jQuery toggleClass example

Toggle class name on click in jQuery

HTML

<div class="form-container">
  <form id="suggested-search" class="search search-suggestions">
    <input type="text" name="search" class="search-input" id="search">
    <ul class="suggestions" id="suggestions-list">
      <li><a href="#visibletag">Visibletag</a></li>
      <li><a href="#something-else">Something else</a></li>
      <li><a href="#click-here">Click here</a></li>
    </ul>
  </form>
</div>
<div class="content">
  <section id="visibletag">This is the most visible Tag, it contains great text</section>
  <section id="something-else">Here you see something else, an other, veryother place</section>
  <section id="click-here">This is the best and uniques tag so you shoud click here</section>
</div>

CSS

body {
  padding: 2%;
}
.search{
  margin-bottom:2em;
}
.suggestions{
  opacity:0;
  pointer-events:none;
  position:absolute;
  right:0;
  top:0;
  width:50%;
  transition:opacity 250ms ease;
}
.search.active .suggestions{
  opacity:1;
  pointer-events:all;
}
section{
  padding:2em 0;
  border-top:1px solid #CCCCCC;
}

JavaScript

;(function($){
  'use strict';
  
  var selectors = {
        form: '#suggested-search',
        input: '#search',
        suggestions: '#suggestions-list',
        content: '.content section',
      },
      class_names = {
        active: 'active',
      },
      $form = $(selectors.form),
      $input = $(selectors.input),
      $suggestions = $(selectors.suggestions),
      suggestions = function(){
        var visible_suggestions = Array.from($suggestions[0].children).filter(function(suggestion){
              return suggestion.style.display !== 'none'
            });
        
        if ( $input[0].value.length > 2 && visible_suggestions.length > 0 ) {
          if ( !$form[0].classList.contains(class_names.active) ) {
            $form[0].classList.add(class_names.active);
          }
        } else {
          if ( $form[0].classList.contains(class_names.active) ) {
            $form[0].classList.remove(class_names.active);
          }
        }
      };
  
  setTimeout(function(){ // move to async to keep the liveFilter code below - just for optical purpose
  // $(document).on('ready', function(){  // use instead of setTimeout usual
    $input.fastLiveFilter(selectors.suggestions, {  // filter articles
      callback: suggestions  // a live search was performed
    });
  // });  // end 'ready' event
  }, 10);  // end setTimeout

})(jQuery);

jQuery.fn.fastLiveFilter=function(list,options){options=options||{};list=jQuery(list);var input=this;var lastFilter='';var timeout=options.timeout||0;var callback=options.callback||function(){};var keyTimeout;var lis=list.children();var len=lis.length;var oldDisplay=len>0?lis[0].style.display:"block";callback(len);input.change(function(){var filter=input.val().toLowerCase();var li,innerText;var numShown=0;for(var...