Changing a div class when clicking on it?
How can I change the class name of a div when I click on it? For instance:
<div class="first_name" onclick="changeClass();" id="first_name"></div>
I want to change it as follows when the user clicks on a div
<div class="second_name" onclick="changeClass();"></div>
I wrote JavaScript as:
<script language="javascript"> function change_autorefreshdiv(){ var NAME = document.getElementById("first_name") NAME.className="second_name" } </script>
It only works for the first instance. This is when loading the page, if I click on it, first_name
will be changed to second_name
. But clicking on it again, it will not return second_name
to first_name
.
You must define the name of the second class. You currently have a function that changes the class name to a hard-coded value, regardless of 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` } }
simple javascript function, put it in your application.js or script tag: - (jQuery must be enabled to run the following function)
function changeClass(){ $("#first_name").attr("class", "class-name-you-want-to-assign"); }
A fairly late response, but a reaction marked as an 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 shorthand for the if-else structure. It checks if className
"second_name". If so, the currentClass
variable will become "first_name"; if it is not (this means "first_name") it will become "second_name".
This is because there is no code for this. Add a little check. I also added some semicolons. I wonder if your script will work even 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>
You need to use if
-statement to cancel it. Here is 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"; } }