How can I change a div class name when clicking on it? Eg:
<
You have to use an if
-statement to reverse it. Here's an example:
function change_autorefreshdiv(){
var NAME = document.getElementById("first_name")
var currentClass = NAME.className;
if(currentClass == "second_name"){
NAME.className = "first_name";
} else {
NAME.className = "second_name";
}
}
That's because there is no code to do so. Add a little check. I also added some semicolons. I wonder if your script would even work the first time.
<script language="javascript">
function change_autorefreshdiv(){
var NAME = document.getElementById("first_name");
if (NAME.className==="second_name")
{
NAME.className="first_name";
}
else
{
NAME.className="second_name";
}
}
</script>
A quite late answer, but the reaction marked as answer can be shortened:
function change_autorefreshdiv(){
var NAME = document.getElementById("first_name");
NAME.className = (NAME.className == "second_name") ? "first_name" : "second_name";
}
This is a shortened notation of the if-else structure. It checks if the className
is equal to "second_name".
If it is, the currentClass
variable will become "first_name", if it's not (meaning it's "first_name"),
it will become "second_name".
simple javascript function, put it in your application.js, or script tag :- (jQuery should be included to run the following function)
function changeClass(){
$("#first_name").attr("class", "class-name-you-want-to-assign");
}
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`
}
}