urosv
urosv

Reputation: 63

JS change image if/else

Im trying to change image when function ends. In IF image should change, and in else, image stays the same.

html

    <img class="owner" id="regina" src="img/uk-profile.jpg" alt="Great Britain">
  <p class="fort"><b>Fort: </b><span  id="wall">1000</span></p>

What i have tried in JS

function finish(){
    var f = document.getElementById('wall');

    if (f>-1) {
        alert("Battle has been won, you now control the region!");
        var g = document.getElementById('regina').src = "img/us-profile";

    }


     else {
        alert("Battle has been lost!");


     }
}

Upvotes: 0

Views: 423

Answers (3)

Mathiasfc
Mathiasfc

Reputation: 1697

When you use

var f = document.getElementById('wall');

In f you have the element not the value of the element, do the following: use .innerHTML to get the value and convert it to int, then you can check if (f > -1)

var f = parseInt(document.getElementById('wall').innerHTML);

function finish() {
  var f = parseInt(document.getElementById('wall').innerHTML);
  if (f > -1) {
    alert("Battle has been won, you now control the region!");
    var g = document.getElementById('regina').src = "http://www.newseum.org/wp-content/uploads/2015/02/xwinner.jpg.pagespeed.ic.iQ7m1XtFLg.jpg";

  } else {
    alert("Battle has been lost!");


  }
}

finish();
<img class="owner" id="regina" src="img/uk-profile.jpg" alt="Great Britain">
<p class="fort"><b>Fort: </b><span id="wall">1000</span></p>

Upvotes: 1

Nebojsa Nebojsa
Nebojsa Nebojsa

Reputation: 1459

If you want to see if wall is more than -1, in your case is 1000, than you need to take value from that element and convert it to a number
Like this:

function finish(){
    var f = document.getElementById('wall').innerHTML;
    f = parseInt(f)

    if (f>-1) {
        alert("Battle has been won, you now control the region!");
        var g = document.getElementById('regina').src = "img/us-profile.src";
    }

     else {
        alert("Battle has been lost!");
     }
}

Upvotes: 1

Noam Gur
Noam Gur

Reputation: 65

Are you trying to check if the text inside "wall" is bigger than -1? if so, this is the way you should check the innerHTML like this:

if (f.innerHTML > -1)

if you are trying to check if wall exist, just check if f returns true:

if(f)

the changing of the src works, it just always go to the else. changing the code to one of the above should help.

Upvotes: 0

Related Questions