April 18, 2012

Swap class on click

Question by Will B

I’ve been trying to figure out how I’m supposed to change a class of an element when you click it.

At the moment i have two classes (cOpen and cClosed). When you open the page the div is set to ‘cClosed’.

<div id="camera" class="cClosed" onClick="cameraToggle('weekLoaderWrapper', 'cameraContainer');">Kamera</div></a>

The things within onClick is not relevant to my question btw..

I’ve also put this script in the code

$('#camera').click(function() {
    $(this).toggleClass('cOpen');
    $(this).toggleClass('cClosed');
});

What I want it to do is to when you press the “camera”-div the class simply swaps to cClosed instead of cOpen, and vice verse when you click it again. This isn’t working atm.

My problem is how i’m supposed to “toggle” the div so it swaps the class of the “camera”-div.

Answer by Starx

Why are you using two classes? Use one class to identify the open and none to denote closed.

$('#camera').click(function() {
    $(this).toggleClass('cOpen');
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!