views:

31

answers:

3

I need to switch my element background image beetwin two images on every click on it.

I have this, byt it swithes color just two times =\

<html>
<head>
    <title>Javascript Change Div Background Image</title>

    <style type="text/css">

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


    </style>

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

            if (imgPath == "url(blue.png)" || imgPath == "") {
                document.getElementById("div1").style.backgroundImage = "url(green.png)";
            }
            else {
                document.getElementById("div1").style.backgroundImage = "url(blue.png)";
            }
        }
    </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>
+1  A: 

The following code should take care of it.

var current_bg = 'green';

function changeDivImage()
{

    if(current_bg == 'green')
    {

        current_bg = 'blue';

    }
    else
    {

        current_bg = 'green';

    }

    document.getElementById("div1").style.backgroundImage = "url('"+current_bg+".png')";

}
Thats right, thanks!
TRAVA
A: 

You probably need to quote the url, that is

backgroundImage = "url('blue.png')" 

I would guess the browser is doing that for you now, which makes the comparison fail. A guess.. A more stable solution might be to maintain a variable to keep track of the current background image instead of comparing strings in css properties.

Alexander Sagen
No, quotes are not neccessary.
TRAVA
+3  A: 

Some browsers are likely giving you the absolute path to the image instead of the relative path you are providing.

Instead of ==, test for the indexOf() position of the url.

Example: http://jsfiddle.net/7Rp2G/2/ (click the button several times to see the url change)

function changeDivImage() {
    var imgPath = new String();
    var div = document.getElementById("div1");
    imgPath = div.style.backgroundImage;

    div.style.backgroundImage = (imgPath.indexOf("blue.png") > -1 || imgPath == "") 
                              ? "url(green.png)" 
                              : "url(blue.png)";

}​

EDIT: Updated to replace the if() with a ternary.

patrick dw
I'll try, thanks for advice.
TRAVA
Thats works too, thanks!
TRAVA