Dan Love Programming
Dan Love Programming

Reputation: 25

Javascript DOM onclick not working for img src

I can't understand why the functions are not being called or if not that why the background image isn't being changed?

script tags:

<script type="text/javascript" >
    function start() 
    {
        document.body.style.backgroundImage = "url('sothback.png')";
        document.body.style.backgroundSize = "100%";
        document.body.style.backgroundRepeat = "repeat-y"; 
    }

    window.onload = start;

    function cartman() 
    {
        document.getElementById("image").style.src = "cartman.png";
    }


    function kenny() 
    {
        document.getElementById("image").style.src = "kenny.png";
    }

</script>

body:

<body>
    <div style="width: 100%; height: 700px;">
        <button onclick="kenny()">Kenny</button>
        <button onclick="cartman()">cartman</button>
        <div style="height: 400px;"></div>
        <center><img src="kenny.png" alt="img" id="image" ></center>
    </div>
</body>

Upvotes: 1

Views: 59

Answers (2)

Dhananjai Pai
Dhananjai Pai

Reputation: 6005

    function start() 
    {
        document.body.style.backgroundImage = "url('sothback.png')";
        document.body.style.backgroundSize = "100%";
        document.body.style.backgroundRepeat = "repeat-y"; 
    }

    window.onload = start;

    function cartman() 
    {
        document.getElementById("image").setAttribute('src',"cartman.png");
document.getElementById("image").setAttribute('alt',"Image of cartman");
    }


    function kenny() 
    {
        document.getElementById("image").setAttribute('src',"kenny.png");
document.getElementById("image").setAttribute('alt',"Image of kenny");
    }

</script>
    <div style="width: 100%; height: 700px;">
        <button onclick="kenny()">Kenny</button>
        <button onclick="cartman()">cartman</button>
        <div style="height: 400px;"></div>
        <center><img src="kenny.png" alt="img" id="image" ></center>
    </div>

Update the style.src to setAttribute. Also consider setting alt tags and title for accessibility and screen readers.

Upvotes: 0

Wicak
Wicak

Reputation: 409

Try with this

 function cartman() {
   document.getElementById("image").setAttribute('src','cartman.png');
 }
 function kenny() {
   document.getElementById("image").setAttribute('src','kenny.png');
 }

Upvotes: 1

Related Questions