What Can JavaScript Do?
       2 - Change HTML Attributes

JavaScript can change images. This example changes an HTML image, by changing the src attribute of an <img> tag:

HTML file: Displayed by browser:
<!DOCTYPE html>
<html>
<body>

<h1>The Light Bulb</h1>

<img id="myImage" onclick="changeImage()" src="../html_beg/images/pic_bulboff.gif" width="100" height="180">

<p>Click the light bulb to turn on/off the light.</p>

<script>
function changeImage() {
    var image = document.getElementById('myImage');
    if (image.src.match("bulbon")) {
        image.src = "../html_beg/images/pic_bulboff.gif";
    } else {
        image.src = "../html_beg/images/pic_bulbon.gif";
    }
}
</script>

</body>
</html>

The Light Bulb

Click the light bulb to turn on/off the light.


BackTable of ContentsNext