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.

2
  • I think you can just use the old code then perform some check right in the handler like this if($(this).hasClass('process1')) ... else ... Commented May 29, 2014 at 8:39
  • possible duplicate of jQuery multiple class selector Commented May 29, 2014 at 8:39

1 Answer 1

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
    }
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.