Sunday, 17 September 2017

javascript - Add class on click then remove a class when clicking outside the div?





I've tried all the ways from the answers here, but have not worked.
So far I have done:






jQuery(function($) {
$(document).ready(function(){
$("#sb-search").click(function(){
$(".sb-search").addClass("sb-search-open");
$("body").click(function(){
$(".sb-search").hasClass("sb-search-open");
$(this).removeClass("sb-search-open");
});
});
});

});










I want to remove the .sb-search-open class after clicked outside the div


Answer





jQuery(function($) {

$(document).ready(function(){
$("#sb-search").click(function(e){
e.stopPropagation();
$(".sb-search").addClass("sb-search-open");

});
$("body").click(function(){
$(".sb-search").removeClass("sb-search-open");
console.log('body')
});

});
});

html,body{
height:100%;
}









First remove click listener on body out side the input click listener.

in input click listener add e.stopPropagation() to stop bubbling of event



jQuery(function($) {
$(document).ready(function(){
$("#sb-search").click(function(e){
e.preventDefault();
e.stopPropagation();
$(".sb-search").addClass("sb-search-open");

});

$("body").click(function(){
$(".sb-search").removeClass("sb-search-open");
});
});
});

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...