Basic JavaScript

advertisements

I'm messing around with the Head First Javascript book. So my question is why doesn't the if clause in my function turnSad() trigger? UPDATE I've tried this in Chrome and FF4. Also, if I were to comment out the if statement, the function will work.

<script type="text/javascript">

    function turnSad() {
        if (document.getElementById("rockImg").src == "rock_happy.png")
            document.getElementById("rockImg").src = "rock.png";
    }

    function touchRock() {
        var userName = prompt("What is your name?", "Enter your name here");

        if (userName) {
            alert("It is nice to meet you " + userName + ".");
            document.getElementById("rockImg").src = "rock_happy.png";
        }
        setTimeout("turnSad();", 1000);
    }

</script>
<img id="rockImg" src="rock.png" alt="iRock"  style="cursor:pointer"
    onclick="touchRock();" />


When accessing the src property (not the attribute), browsers may automatically resolve relative paths and give back the absolute path including the protocol, domain, port, etc.

To get or change the attribute value, use getAttribute and setAttribute.

image.getAttribute("src");

image.setAttribute("src", "someImage.png");

See this example.