1

I have "n" different clasess

 .classOne
 .classTwo
 .classThree
 .classFour
   ....
 .classN

I want to bind .classTwo & unbind the rest except .ClassOne, How Should I do that?

   $("#container").off("click"); /*except classOne*/
  $("#container").on("click.ClassTwo",function...

HTML

     <DIV class="classOne">[Show alert]</div>
     <DIV class="classTwo">[Click dont show anything]</div>
     <DIV class="classThree">[Show alert]</div>
     <DIV class="classFour">[Show alert]</div>
     <DIV class="classFive">[Show alert]</div>

After clickin on this button, the click event deactivates for everyone excepts classOne ...(If you click it it stills shous an alert) and at the same time .classTwo gets the capacity to show an alert after clicking

         <DIV class="button">[]</div>

So, at the end the arrangement would be:

     <DIV class="classOne">[Show alert]</div>
     <DIV class="classTwo">[Show alert]</div>
     <DIV class="classThree">[Click dont show anything]</div>
     <DIV class="classFour">[Click dont show anything]</div>
     <DIV class="classFive">[Click dont show anything]</div>....
joe
  • 209
  • 2
  • 10

2 Answers2

2

If I understand what you are saying, they have a function bound to them already and then when you click on the button you want to unbind all and then rebind except for .classTwo which you can do like this:

$('.button').on('click', function() {
    $('div').off('click');
    $('div').not('.classTwo').on('click', function() {
        // show alert
    })
})
CumminUp07
  • 1,668
  • 1
  • 5
  • 17
  • What do you understand by writing this? `$('div').not('.classTwo').not('.classFifty').off()` ? Do this turn off everything excepts `.classTwo` and `.classFifty`? – joe Mar 15 '18 at 19:29
  • if you did `$('div').not('.classTwo').not('.classFifty').off('click')` that would unbind the click function from every div but classes `.classTwo` and `.classFifty` – CumminUp07 Mar 15 '18 at 19:33
  • terrific. this `.not()` method was what I was looking for. thank you!! – joe Mar 15 '18 at 19:36
  • 1
    Glad i could help – CumminUp07 Mar 15 '18 at 19:37
1

Add your classes to an array so they're more easy to manage, then join that array & use as your jQuery selector.

classList = ['One','Two','Three'...];

// remove 'One' from the classList if needed.
var index = classList.indexOf('One');
if (index > -1) {
    array.splice(index, 1);
}
classes = classList.join(' ');

// the jquery call, notice that we're using a string created by the .join() function called on our array of classes.
$('#container').on('click',classes,function(e){ /* ... */ }


// you can also loop one array and push it's items to a second one, might not be needed, but could help your work.
classes = [];
for(var thisClass in classList){
  classes.push('class'+classList[thisClass]);
}

further reading: How do I remove a particular element from an array in JavaScript?

admcfajn
  • 1,688
  • 3
  • 18
  • 26