How can I remove a class from an element when clicked anywhere on the page?

I'm trying to hide an element when you click anywhere on the page but a div, and if you click on a div then it should switch 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 using 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');
});

      

+3


source to share


2 answers


You will find the solution here 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>
      

Run codeHide result


0


source


In this line:

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

      

you forgot to pass to $event

your function. It should look like this:



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

      

and this code should work.

Working fiddle: http://jsfiddle.net/cfgr9/540/

0


source







All Articles