2

I'm using the class btn1 to control the display of some buttons.

I have a click function set up that works fine

$('#rotation').on('click', '.btn1'...

This calls the same click function for all btn1 buttons.

I'm trying to figure out how to have the same display class, but call different functions for each button eg

$('#rotation').on('click', '.btn1 process1'... 

when this is clicked

<div class="btn1 process1"> 

and

$('#rotation').on('click', '.btn1 process2'... 

when this is clicked

<div class="btn1 process2"> 

They aren't working. Is it possible to do, or do I need to set up IDs for each button, and set the click functions to listen for the IDs and not class?

Thanks for your time and help.

Shaun
  • 2,043
  • 3
  • 27
  • 36
  • I think you can just use the old code then perform some check right in the handler like this `if($(this).hasClass('process1')) ... else ...` – King King May 29 '14 at 08:39
  • possible duplicate of [jQuery multiple class selector](http://stackoverflow.com/questions/1041344/jquery-multiple-class-selector) – James Donnelly May 29 '14 at 08:39

1 Answers1

8

jQuery selectors follow CSS rules, so if you want to target an element with two classes, don't use a space between the class names, like this:

$('#rotation')
    .on('click', '.btn1.process1', fn)
    .on('click', '.btn1.process2', fn);

Alternatively you can have a single click handler and use hasClass to identify the button clicked:

$('#rotation').on('click', '.btn1', function() {
    if ($(this).hasClass('process1')) {
        // do something
    }
    else if ($(this).hasClass('process2')) {
        // do something else
    }
})
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339