2

I want a div to switch its class (toggle) onclick and then revert back to original class onclick again

My code is:

 function myfunc() {
    //the code over here
 }
.normal { 
  width:25%;
  height:25%;
  background: #f00;
}

.active { 
  width:100%;
  height:100%;
  background: #f00;
}

#div{}
<body>
  <div id="div" onclick="myfunc()">click here</div>
</body>
A-Sharabiani
  • 17,750
  • 17
  • 113
  • 128
Umesh Meena
  • 59
  • 1
  • 2
  • 4
  • 2
    Can you try to provide "the code over here" and see what is wrong? I don't think it works right now :p. Possible duplicate of: http://stackoverflow.com/questions/507138/how-do-i-add-a-class-to-a-given-element – porfiriopartida Sep 29 '13 at 06:23
  • Please show your attempted code in the placeholder `the code over here` in you question.. – PSL Sep 29 '13 at 06:27

10 Answers10

12

using pure js:

<div id="div" class="normal" onclick="myfunc(this)">click here</div>

js

function myfunc(div) {
  var className = div.getAttribute("class");
  if(className=="normal") {
    div.className = "active";
  }
  else{
    div.className = "normal";
  }
}
Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
Nishad K Ahamed
  • 1,374
  • 15
  • 25
3

Move away from obtrusive JavaScript, bind the event-handlers in the JavaScript of the page, not in the HTML (this makes for easier future maintenance):

function classToggle() {
    this.classList.toggle('class1');
    this.classList.toggle('class2');
}
document.querySelector('#div').addEventListener('click', classToggle);

JS Fiddle demo.

David Thomas
  • 249,100
  • 51
  • 377
  • 410
3

Use:

// hasClass
function hasClass(elem, className) {
 return new RegExp(' ' + className + ' ').test(' ' + elem.className + ' ');
}
// toggleClass
function toggleClass(elem, className) {
 var newClass = ' ' + elem.className.replace( /[\t\r\n]/g, " " ) + ' ';
    if (hasClass(elem, className)) {
        while (newClass.indexOf(" " + className + " ") >= 0 ) {
            newClass = newClass.replace( " " + className + " " , " " );
        }
        elem.className = newClass.replace(/^\s+|\s+$/g, '');
    } else {
        elem.className += ' ' + className;
    }
}
document.getElementById('div').onclick = function() {
    toggleClass(this, 'active');
}
div {
    margin:20px;
    padding:10px 15px;
    background:#FFD202;
    border-radius:5px;
    color:#222;
    display:inline-block;
    text-decoration:none;
}
.active {
    background:#000;
    color:#FFD202;
}
<div id="div" href="#">Click a few times, toggle me!</div>
Ben
  • 257
  • 1
  • 15
2
function myFunc(e) {
    if(e.className == 'active') {
        e.className = 'normal';
    } else {
        e.className = 'active';
    }
}

then have:

<div id="div" onclick="myFunc(this)">blah</div>

pretty sure that is answered in a number of other questions round here too.

floodpants
  • 133
  • 7
2

I've been looking for a solution myself where I want to toggle between two images with pure JavaScript. I think this is quite an effective method of using JavaScript. (I had to switch between a plus and a minus image sign on user click.)

HTML

<a href="#" class="plus" onclick="toggleClass(this,'minus')">Text here</a>

CSS

.plus {
  background-image: url(../img/plus-circle-grey.svg);
}

.minus {
  background-image: url(../img/minus-circle-grey.svg);
}

JavaScript

function toggleClass(e,c) {
    (e).classList.toggle(c);
}

Works like a charm.

Tiberiuscan
  • 413
  • 4
  • 8
0

do:

function myfunc(){
  var divEle = document.getElementById("div"),
      current_class = divEle.className;
  divEle.className = (current_class == "active") ? "normal" : "active";
}
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
0

A good way to approach your dilemma is using the classList API. I switch classes using nested for loops (for repeating instances of a class) and query the document like so:

var desiredElement = document.querySelectorAll('.light');

function switchTheme() {
    for (var i = 0; i < desiredElement.length; i++) {
        if (desiredElement[i].classList.contains('light')) {
            desiredElement[i].classList.remove('light');
            desiredElement[i].classList.add('dark');
        } else if (desiredElement[i].classList.contains('dark')) {
            desiredElement[i].classList.remove('dark');
            desiredElement[i].classList.add('light');
        }
    }
}

By adding a button or hyperlink to either perform this function onclick or as href, I can toggle any element in the HTML document containing the light or dark class and effectively make a toggle switch to switch the sub design classes.

I used this to create a dark theme for a website that can toggle to a lighter theme by the user if desired.

var desiredElement = document.querySelectorAll('.light');

function switchTheme() {
  for (var i = 0; i < desiredElement.length; i++) {
    if (desiredElement[i].classList.contains('light')) {
      desiredElement[i].classList.remove('light');
      desiredElement[i].classList.add('dark');
    } else if (desiredElement[i].classList.contains('dark')) {
      desiredElement[i].classList.remove('dark');
      desiredElement[i].classList.add('light');
    }
  }
}
.light {
  background-color: #ddd;
}

.dark {
  background-color: #333;
}
<DOCTYPE HTML>
<html>
  <body class="light">
    <button onclick="switchTheme()">Toggle</button>
  </body>
</html>
swordkorn
  • 1
  • 1
0

There are already quite a few answers but I think this is the simplest / most succinct approach here:

<div onclick="$(this).toggleClass("active")">click here</div>
Felix Eve
  • 3,811
  • 3
  • 40
  • 50
0

If you want to switch/swap class-A and class-B, toggle both classes:

function myFunc(element) {
    element.classList.toggle("class-A");
    element.classList.toggle("class-B");
}

And

<div onclick="myFunc(this)" />
A-Sharabiani
  • 17,750
  • 17
  • 113
  • 128
-1

Try it with jquery may this help

html-

<div id="div1" class="normal">click here</div>
<div id="div2" class="normal">click here</div>

css-

.normal{ width:25%;height:25%;background: #f00;}
.active{ width:100%;height:100%;background: #f00;}

jquery-

$(document).ready(function(){
                $(".normal").click(function(){
                    var thisobj =  $(this);
                    if(thisobj.hasClass("active"))
                    {
                        $(this).removeClass("active");
                    }else
                    {
                        $(this).addClass("active");
                    }
                });
            });

jsfiddle

Ronjon
  • 1,789
  • 4
  • 16
  • 26