Guillermorivia Guillermorivia - 4 months ago 8
HTML Question

Disable OnClick Event Until Another One Is Triggered First

I have 6 divs (

.selector
) set to do (
onclick
):


  1. Show all tables

  2. Show Nº1, Hide rest

  3. Show Nº2, Hide rest

  4. ...

  5. Show Nº5, Hide rest



They also toggle a class
"activated"
that changes the background color.

What I'm trying to do is that once I click on "Show Nº1, Hide rest" disable the click option (On this div) until I click in another one first like "Show all tables" or "Show Nº2, Hide rest".

Something like the "once function" but that resets as soon as another div is activated. Any way to do this?

enter image description here

Here is my CSS

.selector {
height: 25px;
width: 25px;
background-color: #702C3D;
margin-left: 2px;
margin-right: 2px;
float: left;
cursor: pointer;
}

.selector.activated {
background-color: #000000;
}


Here is my JavaScript

$('.selector').on('click', function(event) {
$('.selector').not(this).removeClass('activated');
$(this).toggleClass('activated');
});

Answer

If you change toggleClass to addClass in your click function. Then, more than 1 click in your .activated will have no effect (as the click is disabled):

$('.selector').on('click', function(event) {
  $('.selector').not(this).removeClass('activated');
  $(this).addClass('activated');
});

Or you can check if the clicked .selector has .activated class like:

$('.selector').on('click', function(event) {
  if($(this).is('.activated')) return;
  $('.selector').not(this).removeClass('activated');
  $(this).toggleClass('activated');
});
Comments