Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
152
rated 0 times [  157] [ 5]  / answers: 1 / hits: 62115  / 13 Years ago, sat, october 29, 2011, 12:00:00

How can I change a div class name when clicking on it? Eg:



<div class=first_name onclick=changeClass(); id=first_name></div>


I want to change it as follows, when a user clicks on the div



<div class=second_name onclick=changeClass();></div>


I wrote the JavaScript as:



<script language=javascript> 
function change_autorefreshdiv(){
var NAME = document.getElementById(first_name)
NAME.className=second_name
}
</script>


It's working for the first instance only. That is on page load, if I click on it, the first_name gets changed into second_name. But clicking on it again, it won't revert the second_name to first_name.


More From » javascript

 Answers
49

You have to define the second class name. Currently, you have got a function which changes the class name to a hard-coded value, independent on the current class name. See also: MDN: if...else



function change_autorefreshdiv(){
var NAME = document.getElementById(first_name);
var currentClass = NAME.className;
if (currentClass == second_name) { // Check the current class name
NAME.className = first_name; // Set other class name
} else {
NAME.className = second_name; // Otherwise, use `second_name`
}
}

[#89380] Friday, October 28, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
johnnaj

Total Points: 490
Total Questions: 109
Total Answers: 104

Location: Zambia
Member since Thu, Jun 25, 2020
4 Years ago
;