Changing The className

essential 0 Tallied Votes 245 Views Share

It performs the toggle function to change the class of the paragraph tags and reverts back to the default class name when user rollout of it. You can embed the CSS style code inside the Head section of your page using HTML style tag. Code is as follows :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Javascript class switcher</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
<!--
/* RED Class */
.red { color: red; text-align: center; }
/* BLUE Class */
.blue { color: blue; text-align: center; }
-->
</style>
<script type="text/javascript">
<!-- BEGIN HIDING
var red = 'red'; 
var blue = 'blue';
function class_switcher(classes)
{ 
   var class = document.getElementById(classes);
 
if ( class.className == red ) 
{ class.className = blue; class.innerHTML = '~Now i\'m with the <b>BLUE</b> class~';
} 
else if ( class.className == blue )
{ class.className = red; class.innerHTML = '~Now i\'m with the <b>RED</b> class~';
} else { class.className = red; } 
}
function normal(id, class, default_value)
{ document.getElementById(id).className = class;
  document.getElementById(id).innerHTML = default_value;
}
// DONE HIDING-->
</script>
</head>
<body>
<p id="first_paragraph" class="blue" onMouseOver="class_switcher('first_paragraph');" onmouseout="normal('first_paragraph', 'blue', '< I\'m from the <b>BLUE</b> class >');"><< I'm from the BLUE class >></p>
<p id="second_paragraph" class="red" onMouseOver="class_switcher('second_paragraph');" onmouseout="normal('second_paragraph', 'red', '< I\'m from the <b>RED</b> class >');"><< I'm from the RED class >>
</p>
</body>
</html>
tekagami 23 Newbie Poster
<script type="text/javascript">
function switchclass(obj){
	 if (obj.className == 'small'){
	 obj.className = "big";
	 }
	else if (obj.className == 'big'){
	 obj.className = "small";
	 }
    }
</script>
<style>
.small { width: 40px; }
.big { width: 100%; }
</style>
<img src="/picture.jpg" class="small" onclick="switchclass(this);">
<img src="/picture.jpg" class="small" onclick="switchclass(this);">

css is up to you

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.