Javascript Change Div Background Image onclick
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.
JavaScript DOM Examples:
You can see the live samples and examples of JavaScript DOM from the following links:
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
<html>
<head>
<title>Javascript Change Div Background 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">
<![CDATA[
function changeDivImage() {
var imgPath = new String();
imgPath = document.getElementById("div1").style.backgroundImage;
if (imgPath == "url(images/blue.gif)" || imgPath == "") {
document.getElementById("div1").style.backgroundImage = "url(images/green.gif)";
}
else {
document.getElementById("div1").style.backgroundImage = "url(images/blue.gif)";
}
}
]]>
</script>
</head>
<body>
<center>
<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()" />
</center>
</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.
Output:
You can see the output of above discussed codes from the following link:
Continue to next tutorial: Javascript Code to Change Text Color of HTML elements to learn how to change the font color of text dynamically.
