I have an anchor with a class name. When I click the anchor I want the class to change. When I click it again, I want it to change back. Simple, but I don't know JS. Thanks

You'd need something along the lines of this

function changeClass(elem, className1,className2)
{
    elem.className = (elem.className == className1)?className2:className1;
}

Then the anchor would look like this

<a href='#' class='class1' onclick='changeClass(this,"class1","class2");'>Hello World</a>

I would like this too except with no onclick. It'll be for two more more buttons that will be changing it's own class. So using this.

Click on any of the buttons, change it's own class.

Please help

These days I would do it in a few lines of jQuery, as that's my framework of choice, and most of my apps are using it.

(function($) {
  $(function() {
    $('target clicked element css selector').click(function(){
      $(this).toggleClass('toggled-class')
    });
  });
})(jQuery);

These days I would do it in a few lines of jQuery, as that's my framework of choice, and most of my apps are using it.

(function($) {
  $(function() {
    $('target clicked element css selector').click(function(){
      $(this).toggleClass('toggled-class')
    });
  });
})(jQuery);

Thank you. I'm also playing with jQuery and was already using the following. Just looking for a way to do this without using any javascript libraries.

$(function()	{

$('.button').click(function() {
$(this).children(".button_slider").toggleClass('button_slider_off');  	
});
						
});

Thank you. I'm also playing with jQuery and was already using the following. Just looking for a way to do this without using any javascript libraries.

Can you wrap up the first solution in a document listener rather than using the onClick?

window.onload=addLinkEvt;
function addLinkEvt(){
var link = document.getElementById('changeclass');
if (link.addEventListener) {
link.addEventListener('click',onLinkEvt, false);
}
}
function onLinkEvt(e){
var className1 = 'c1';
var className2 = 'c2';
elem.className = (elem.className == className1)?className2:className1;
}

Edited 7 Years Ago by codejoust: n/a

This article has been dead for over six months. Start a new discussion instead.