Javascript Change Div Background Image onclick

by top54u.com 25 Jun, 2008
Spotlight.....

Here you will learn how to change the backgroundImage CSS property of div HTML <div> element using its onclick event. Javascript DOM document object consists of getElementById method that further provides style object. Javascript style object enables you to get or set the various CSS style properties dynamically. The Javascript style object provides the backgroundImage property of CSS style that can be used to change the background image of HTML <div> DIV elements or any other HTML element that supports this property. Pass the id attribute value of <div> tag whose backgroundImage you want to change dynamically.

 

Syntax of Javascript Style Object to Change Background Image

document. elementById("id"). style. backgroundImage = "value";

 

style object and backgroundImage property both are case sensitive in Javascript so use the same pattern of letters to implement the code syntax.

 

Example of Javascript Change Div Background Image onclick

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html>


<head>


<title>Javascript Change Div Image</title>


<style type="text/css">


#div1 {
width:100px;
height:30px;
background-image:url(../images/blue.gif);
}



p {
font-family:Verdana;
font-weight:bold;
font-size:11px
}


</style>


<script language="javascript" type="text/javascript">


function changeDivImage()
{
    document.getElementById("div1").style.backgroundImage = "url(../images/green.gif)";
}


</script>


</head>


<body>


<p>
This Javascript Example will change the background image of<br />
HTML Div Tag onclick event.
</p>


<div id="div1"></div>


<br />


<input type="button" value="Change Background Image" onclick="changeDivImage()" />


</body>


</html>

 

In the above example there is a code for embedded CSS styles. background-image CSS property is used to set the background image of div tag. This property is accessed in Javascript code using style object.

Download the following images to try them with sample Javascript code:


blue.gif

 


green.gif

Spotlight.....

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , , , , , , , , , , , ,

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

8/23/2008 8:56:47 PM

OUR SPONSORS[+ advertise here]
related videos.....
recent posts.....
top54u ezines.....