Skip to content
Advertisement

Change image src to a local image using javascript?

First time ever touching javascript here, so bear with me. My file structure looks like so:
enter image description here

I want to change the image in my HTML using js. Here’s the relevant HTML code:

    <!DOCTYPE html>
<html>
    <head>
        <title>Assignment 3A</title>
        <meta charset="UTF-8">
        <link rel="stylesheet" type="text/css" href="style/assignment_3.css">
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
        <script src="data/data.js"></script>
        <script src="script/htmlMaker.js"></script>
        <script src="script/assignment_3.js"></script>
        <script id="news-detail-template" type="text/html">
                    <img class='news_photo' src='{{photo}}' >
        <div class='news_heading'>{{heading}}</div>
        <div class='date'>{{Date}}</div>
        <div class='news_detail'>{{details}}</div>          
        </script>  
        <script id="news-item-template" type="text/html">
        <div news_id='{{id}}' class='news_item' > {{heading}} </div> 
        <img class='news_img' src='data/NBA.jpg'>
        </script>         
    </head>
    <body>
        <div class="newsDiv">
            <div class="left">Latest</div>
            <div id="news" class="marquee"></div>
            <img id="toggle" class="right" src="data/pause.png" onclick="toggle(this)">
        </div>
        <div id="detail" class="detail">

        </div>
    </body>
</html>

And then the corresponding js code in assignment_3.js:

function toggle(image) {
    if (image.src != "data/pause.png")
    {
        image.src='data/pause.png';
    }
    else if (image.src == "data/pause.png")
    {
        image.src='data/play.png';
    }
}

Obviously, something is amiss here, as the browser doesn’t seem to recognize my image paths at all. How would I go about doing this correctly?

Advertisement

Answer

When you use image.src, it returns the full path of the image. In the if condition, you only checks the relative path of the image. To check for the relative path of the image, you can use image.getAttribute('src').

function toggle(image) {
  if (image.getAttribute('src') == "data/pause.png") {
    image.setAttribute('src', 'data/play.png');
  } else {
    image.setAttribute('src', 'data/pause.png');
  }
}
<body>
  <div class="newsDiv">
    <div class="left">Latest</div>
    <div id="news" class="marquee"></div>
    <img id="toggle" class="right" src="data/pause.png" onclick="toggle(this)">
  </div>
  <div id="detail" class="detail">

  </div>
</body>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement