views:

31

answers:

4

I have a .click() on several buttons. Each .click() calls a function. The function needs to know which button called it so that it can show or hide different content and change the styles of the other buttons. The function has an event object passed to it.

Is there a way I can get the current class that the event object has?

+1  A: 

You can get the class with .className or .attr("class"), though what you probably want is to have this refer to the button, for example:

$(".selector").click(myFunction);

function myFunction() {
  //this == button that was clicked
  var c = this.className;
}

Or an inline function:

$(".selector").click(function () {
  var c = this.className;
});
Nick Craver
A: 

As long as you are passing this to a function (though depending how you are doing this, some code would be nice!), if you pass e as the first parameter in the function then you can use e.target.className to get the class, or, with jQuery $(e.target).attr('class');

Alex
A: 

Couldn't you make different functions for the different .click() calls?

Kyle
I'm going to end up with between 25 and 35 .click() calls. I'd rather they all call one function rather than have 25 or 35 different functions.
Supermighty
+2  A: 
$('myButton').click(function() {
    var className = this.className; // This will give you the whole class string of the clicked element
    var hasClass = $(this).hasClass('myClass'); // This will tell you (true or false) whether the clicked element has class 'myClass'
});
Ryan Kinal
This is good, because I won't know the class name before hand.
Supermighty
In this case is this the same as the event object that click passes to the function?
Supermighty
It's not the event object, it's the DOM element that triggered the click. (Which would be the same as the `target` or `srcElement` of the event object).
Ryan Kinal