umanga shrestha
umanga shrestha

Reputation: 406

add remove class with time limit with jquery

I have a search box that should only show when an icon is clicked. After the box appears when an icon is clicked it should disappear in some interval of time (like 5 seconds), even when user clicks on the other part of the body.

$(".icon").click(function()){
    $("search-box").addClass("active");
});

Upvotes: 0

Views: 984

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115222

Do something like this

var box = $(".search-box");

// Code for closing if anywhere else is clicked
$(document).click(function() {
  box.removeClass('active');
});

$(".icon").click(function(e) {
  e.stopPropagation();
  // preventing parent click handler 

  box.addClass("active");
  // Adding class to the box

  setTimeout(function() {
    box.removeClass('active');
  }, 5000)
  // Code for removing class after 5 second
 
})

box.click(function(e) {
  e.stopPropagation();
  // preventing parent click handler 
});
.search-box {
  display: none
}
.active {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="icon">click</button>

<div class="search-box">Box to display</div>

Upvotes: 1

Daniel Cheung
Daniel Cheung

Reputation: 4819

Are you looking for this?

Jquery

var icon = $(".icon");
icon.click(function () {
    $(".search-box").addClass("active");
    setTimeout(function () {
        icon.fadeOut();
    }, 5000)
})

Upvotes: 1

Related Questions