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!
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.
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.
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 }); });
Using jQuery:
$('#Button').click(function(){ $(this).addClass("active"); });
This way, you don't have to pollute your HTML markup with onclick
handlers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With