PrettyPotatu
PrettyPotatu

Reputation: 11

Comparing the source of an Image (If statement)

So, I'm trying to create an If statement to compare the source of my Image so I can change it with the corresponding reversed image.

function changeBack() {
let image = document.getElementById('product__picture');  
    console.log(image);
if(image.src === 'assets/red.jpg'){
    image.src = ('assets/red-reversed.jpg');
    console.log(image);

} else if(image.src === 'assets/orange.jpg'){
    image.src = ('assets/orange-reversed.jpg');
}

HTML:

<article class="product">
       <h2 class="hidden">Display Picture</h2>
       <img id="product__picture" src="assets/red.jpg" alt="Laptop case">
</article>

Here's my onclick button:

 <article id="reverse">
        <h2 class="subtitle">Select side</h2>
        <div id="reverse__container">
        <p id="front" class="reverse__text">Front</p>
        <p id="back" class="reverse__text" onclick="changeBack();">Back</p>
    </div>
    </article>

Upvotes: 1

Views: 384

Answers (2)

Fadi Tash
Fadi Tash

Reputation: 112

compare the src property of the images and not the image Objects themselves! You also do not need the extra parentheses around the string properties. furthermore, please use === instead == for equality comparisons of the same type. I almost never use double equals.

function changeBack() {
  let image = document.getElementById('product__picture');  

  if(image.src === 'assets/red.jpg'){
      image.src = 'assets/red-reversed.assets'
  } else if(image.src === 'assets/orange.jpg') {
      image.src = 'assets/orange-reversed.jpg';
  }
}

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386560

You need to check src property and not the object.

BTW, strings do not need parentheses around.

function changeBack() {
    let image = document.getElementById('product__picture');

    if (image.src === 'assets/red.jpg') {
        image.src = 'assets/red-reversed.assets';
    } else if (image.src === 'assets/orange.jpg') {
        image.src = 'assets/orange-reversed.jpg';
    }
}

Upvotes: 2

Related Questions