rowdy rowdy - 1 year ago 82
CSS Question

How to remove a class from an element when click anywhere on the page?

I'm trying to hide an element when click anywhere on the page but the div, and if you do click while over the div, then it should toggle the class.

jQuery -

$('.onclick-dropdown-link').on('click', function(e) {
e.preventDefault();
var $this = $(this);
var id = $this.attr('href');
$('.onclick-dropdown').not(id).removeClass('open');
$(id).toggleClass('open');
});


HTML -

<a class="onclick-dropdown-link" href="#test-div"></a>
<div id="test-div" class="onclick-dropdown">
<p>Lorem Ipsum<p>
</div>


CSS -

.onclick-dropdown {
opacity: 0;
visibility: hidden;
z-index: 999;
}
.onclick-dropdown.open {
opacity: 1;
visibility: visible;
}


Already tried with below methods -

$(document).on('click', function() {
$('.onclick-dropdown').not(id).removeClass('open');
});

$(document).on('click', function() {
$('.open').not(id).removeClass('open');
});

$('.onclick-dropdown-link').on('click', function() {
e.stopPropagation(); // This is the preferred method.
return false; ;
});

$(document).on('click', function() {
$('.onclick-dropdown.open').removeClass('.open');
});

Answer Source

Here you go with a solution https://jsfiddle.net/t3y5zo2t/

$('.onclick-dropdown-link').on('click', function(e) {
   e.preventDefault();
   e.stopPropagation();
   var $this = $(this);
   var id = $this.attr('href');
   $('.onclick-dropdown').not(id).removeClass('open');
   $(id).toggleClass('open');
});

$('body:not(.onclick-dropdown-link)').click(function(e){
  $('#test-div').removeClass('open');
});
.onclick-dropdown {
    opacity: 0;
    visibility: hidden;
    z-index: 999;
}
.onclick-dropdown.open {
    opacity: 1;
    visibility: visible;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<a class="onclick-dropdown-link" href="#test-div">test</a>
<div id="test-div" class="onclick-dropdown">
    <p>Lorem Ipsum<p>
</div>
</body>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download