Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript/Jquery to change class onclick?

Tags:

javascript

I want to change a class onclick. What I have at the moment:

<script>
function changeclass() {

var NAME = document.getElementById("myclass")

NAME.className="mynewclass"

} 
</script>

But, ofcourse, its not working. Also, it should revert to previuos state onclick again.

My html:

<div id="showhide" class="meta-info" onclick="changeclass();">

So, whenever I press on #showhide myclass should change to mynewclass. Thanks for help in advance!

like image 535
funguy Avatar asked Aug 10 '11 16:08

funguy


Video Answer


2 Answers

With jquery you could do to sth. like this, which will simply switch classes.

$('.showhide').click(function() {
    $(this).removeClass('myclass');
    $(this).addClass('showhidenew');
});

If you want to switch classes back and forth on each click, you can use toggleClass, like so:

$('.showhide').click(function() {
    $(this).toggleClass('myclass');
    $(this).toggleClass('showhidenew');
});
like image 154
SunnyRed Avatar answered Nov 08 '22 08:11

SunnyRed


Your getElementById is looking for an element with id "myclass", but in your html the id of the DIV is showhide. Change to:

<script>
function changeclass() {

var NAME = document.getElementById("showhide")

NAME.className="mynewclass"

} 
</script>

Unless you are trying to target a different element with the id "myclass", then you need to make sure such an element exists.

like image 27
Griffin Avatar answered Nov 08 '22 07:11

Griffin