Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery addClass onClick

The setting is easy; I want to be able to add a class to (in this case) a button when onClick-event is fired. My problem is that I haven't found a way to pass the button itself as the parameter to the function. I'd like to do something like:

<asp:Button ID="Button" runat="server" onclick="addClassByClick(this)"/> 

And then a javaScript function something like this:

function addClassByClick(button){     button.addClass("active") } 

I know I've got a lot of errors here, but that's why I'm posting. I've tried different scenarios with jQuery and without jQuery but I always end up with a broken solution (clicks suddenly stop coming through, class not added etc etc) so I decided to ask the pro's.

Any suggestion to what I can try? Thanks for reading editand all the help!

like image 371
Phil Avatar asked Aug 25 '10 14:08

Phil


People also ask

What does addClass do in jQuery?

The addClass() method adds one or more class names to the selected elements. This method does not remove existing class attributes, it only adds one or more class names to the class attribute. Tip: To add more than one class, separate the class names with spaces.

How do I add a class to Onclick?

To add a class on click of anchor tag, we use addClass() method. The addClass() method is used to add more property to each selected element. It can also be used to change the property of the selected element.


2 Answers

It needs to be a jQuery element to use .addClass(), so it needs to be wrapped in $() like this:

function addClassByClick(button){   $(button).addClass("active") } 

A better overall solution would be unobtrusive script, for example:

<asp:Button ID="Button" runat="server" class="clickable"/> 

Then in jquery:

$(function() {                       //run when the DOM is ready   $(".clickable").click(function() {  //use a class, since your ID gets mangled     $(this).addClass("active");      //add the class to the clicked element   }); }); 
like image 103
Nick Craver Avatar answered Sep 22 '22 14:09

Nick Craver


Using jQuery:

$('#Button').click(function(){     $(this).addClass("active"); }); 

This way, you don't have to pollute your HTML markup with onclick handlers.

like image 36
Benjamin Wohlwend Avatar answered Sep 25 '22 14:09

Benjamin Wohlwend