Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the class of a div when clicking on it?

Tags:

javascript

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.

like image 679
user632347 Avatar asked Oct 29 '11 19:10

user632347


2 Answers

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`
    }
}   
like image 61
Rob W Avatar answered Sep 20 '22 02:09

Rob W


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");
    }
like image 25
Nishutosh Sharma Avatar answered Sep 20 '22 02:09

Nishutosh Sharma