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>

2
  • 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: stackoverflow.com/questions/507138/… Commented Sep 29, 2013 at 6:23
  • Please show your attempted code in the placeholder the code over here in you question.. Commented Sep 29, 2013 at 6:27

10 Answers 10

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";
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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>

Comments

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.

5 Comments

added more info, this will apply to any div, rather than hard coding the div id into the JS like my orig version.
Why are you calling getElementById when the onclick function passes the element, not the ID?
fixed the post to use e.id like it should. Brain fade when i wrote it. Thanks for the pickup. Tested the above this time also, works for me.
Why not just e.className?
because that would be far too logical!! yeah my bad, fixed again.
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.

Comments

0

do:

function myfunc(){
  var divEle = document.getElementById("div"),
      current_class = divEle.className;
  divEle.className = (current_class == "active") ? "normal" : "active";
}

Comments

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>

Comments

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>

2 Comments

This is not only javascript
The question isn't just about javascript. It asks how to toggle a class on a div. A div is html. I'm only using javascript to toggle the class.
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)" />

Comments

-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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.