Javascript Change Div Background Image onclick

Updated on 23 Mar 2012,
Published on 30 Jun 2008

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:

Change Div Background Image

Continue to next tutorial: Javascript Code to Change Text Color of HTML elements to learn how to change the font color of text dynamically.

24 Responses to "Javascript Change Div Background Image onclick"
Simon
Thankyou, very effective!
Thank you ! It really helps.
thank you. it helped me a lot !
Adisa
Hi,

first of all, thank you for putting this code online for people like me that are just starting out using javascript.

I used this code to change the background image. But instead of using a button I want to use an "empty" hyperlink (that I positioned where I want it to be)to change the background image. But this didn't work. Than I copied and pasted the coding for the button, but it still didn't work.

Can somebody please tell me what I am doing wrong and if it is possible to use a hyperlink instead of a button??


for example:

<script language="javascript" type="text/javascript">
function changeDivImage()
{
var imgPath = new String();
imgPath = document.getElementById("content").style.backgroundImage;

if(imgPath == "url(../slices/sister_content.jpg)" || imgPath == "")
{
document.getElementById("content").style.backgroundImage = "url(../slices/sister_content.jpg)";
}
else
{
document.getElementById("content").style.backgroundImage = "url(../slices/sister_content2.jpg)";
}
}
</script>

#content {
height: 338px;
width: 563px;
background-image: url(../slices/sister_content.jpg);
background-repeat: no-repeat;
position: absolute;
left: 110px;
top: 100px;
}
#prev {
position: absolute;
left: 25px;
top: 242px;
height: 25px;
width: 140px;
}
<div id="content">
<a id="prev" href="#" value="Change Background Image" onclick="changeDivImage()"></a></div>

Ezineasp.net
Hi Adisa You have not used the style tag to wrap up the CSS code. Please check your code... if it is the only problem?
Adisa
Hi thank you for your response. I've put the CSS code in an external css file which I linked to in my html. So it can't be that. Thank you. Adisa
Ezineasp.net
Hello again!!! There is one mistake... Interchange the image urls inside the if-else conditions. It will solve the issue. Try this and reply.
Adisa
That was it! Thank you very much!! Adisa
Adisa
It is solved by the help of www.ezineasp.net! I had to interchange the urls inside the if/else conditions Again, many thanks! Adisa
AshaSattane
hi, I have used the background image change java script compatible in all browsers. if any one can get help from this can use.. //Java Script Function function funCheck(ID) { /* Code to change image state */ var refr = document.getElementById(ID); var ImgPath=new String(); imgPath = refr.style.backgroundImage; var searchindex=imgPath.search("checkbox.png"); if(searchindex==-1 || imgPath == "") { alert("in if "+imgPath+" Index "+searchindex); refr.style.backgroundImage="url(images/checkbox.png)"; } else { refr.style.backgroundImage="url(images/checkbox_no.png)"; } }
Ian
I have used this code and it has worked, thank you so much. And I have the onclick="changeDivImage()" and everything is working, however It works when changing and changing back only once, how can i get it so that the onClick function will always change the background with each click???
Casey
You might want to go back through your little tutorial here and proof-read your syntax.
Hey guys am not very good with js, none the less trying my hand at it. Besides I need it to create prototypes of my design. Below is my code. Basically I am trying to create child divs on a certain event. Event - User enters numbers in a numeric spinner. Based on the value on the numeric spinner I want that many number of divs. That is working but I want each of these child divs to have a unique id. function createDiv1() { var divTag = document.createElement("div"); var a = parseInt(document.getElementById("image_1").style.height); var t = new Number(15); var r = new Number(0); divTag.id = "div1"; divTag.setAttribute("align","center"); divTag.className ="dynamicDiv"; /* divTag.innerHTML = "Manip1";*/ document.getElementById("image_1").appendChild(divTag); } This is the code. Please help. Also is it possible to move(animate) these child divs?
Ezineasp.net
Hi Amrutha

You can try the following Javascript code to generate dynamic Div elements with unique ids:

function createDiv() {
// you can pass max number retrieved from numeric spinner
for (var i = 1; i <= 10; i++) {
var divTag = document.createElement("div");
divTag.id = "div" + i;
divTag.setAttribute("align", "center");
divTag.style.margin = "0px auto";
divTag.className = "dynamicDiv";
divTag.innerHTML = "<b>" + i + "</b>";
document.getElementById('container').appendChild(divTag);
}
}

Yes you can animate the child divs, but you need to learn JQuery for implementing the dynamic effects.
Hey thanks man, the code works well....I also wanted to change images dynamically in these divs. This the number of divs whose background image will change is based on the value of the second spinner. Now the issue is that except the first div ( div1) none of the other div bg images change :(. function increment2() { var x = new Number(1); var l = new Number(0); var m = new Number(9); var y = parseInt(document.getElementById("input_2").value); var z = parseInt(document.getElementById("input_1").value); var b = document.getElementById("input_2"); var c = document.getElementById("input_3"); if(z>y) { b.value = x + y; createDiv2(); removeElement3(); /*changeDivImage2();*/ } if(z>=y) { c.value=z-b.value; } else if(z";*/ document.getElementById('image_2').appendChild(divTag); document.getElementById('image_1').document.getElementById('div'+x).style.backgroundImage="url(birds-shwd.png)";/*THIS LINE DOES NOT WORK*/ }}
Ezineasp.net
Hello @Amrutha

Please tell explain the function of second spinner you are talking about. Are you trying to set the background images randomly or is there any sequence of images?
So basically the second spinner sets the value of the number to be deducted from the first number. This is a subtraction operation. First column has objects corresponding to no. entered ok Second column has objects corresponding to no. to be deducted from first. And third column displays no. of objects remaining in the first. But here whenever an object is being deducted from column 1 and shadow is formed in its place in the first column. Shadow shows that there was an object present there. Now basically I am creating divs for each object. So based on the value of the spinners divs are generated dynamically. Also in case of second spinner 2 operations are happening. 1) Object generation in second column corresponding to no. entered 2) Corresponding no. of objects in first column change bg image(thts they become shadows of the object)--->This is my main problem area
Ezineasp.net
@Amrutha

Ok. Remove your following code statement:

document.getElementById('image_1').document.getElementById('div'+x).style.backgroundImage = "url(birds-shwd.png)";

use only following statement to set the backgroundImage:

document.getElementById('div' + parseInt(x - 1)).style.backgroundImage = "url(birds-shwd.png)";


Try this code.. hope it will help you.
Cheers!
hey i want to use javascript to change the width ofa background image. tried using document,getElementById('someId').style.backgroundImage.width
deo
thanks..:)
rhys
hello i have got this working. yet it only works to change the image once, and then back again. then it no longer works. is it possible to have the button to continually change the background image upon repeated clicks?? many thanks in advance.!
Ezineasp.net
@Rhys Try the following code: <script language="javascript" type="text/javascript"> 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> There is a bug in the old code. The JavaScript gets the url value in double quotes which is not allowing the code to change the image multiple times the button is clicked. Use the above code to resolve the issue. Good Luck ;)
Rhys
thanks. works in Firefox. just chrome that still has issues with it. thank you again.!!
Engr. Saiful Islam
Very Nice
Leave a Comment
* required
* required
* will not be published
* optional
* hint: http://www.example.com
  • Subscribe via Email