Home > Net >  How to optimize the currently if...else based conditional-statement for an image toggle approach?
How to optimize the currently if...else based conditional-statement for an image toggle approach?

Time:11-18

hello is there any other way to get the same result as we see down goal is : changing the "src" attribute with one button and function

<img id="image" src="path of picture1" width="160" height="120">
<button type="button" onclick="test()">over here </button>

<script>
  let smile = true  
  let test = () => {
    if (smile == true) {
      document.getElementById("image").src = "path of picture2";
      smile = false
    } else {
      document.getElementById("image").src = "path of picture1";
      smile = true
    }
  }
</script>

whenever I click the button the browser shows me picture2 then if I click again shows me picture1 and this can be done over and over again please share your solution for this

CodePudding user response:

Here is another solution, wich is just 5 lines of JS. It uses if-else oneliners, to wich a detailed guide can be found here.

I also used the HTML data-attribute instead of a variable: data-smile="false"

I removed the id of the Element because you can just select it via the data-attribute.

let img = document.querySelector('[data-smile]');
img.onclick = () => {
    img.dataset.smile = img.dataset.smile == "true" ? "false" : "true";
    img.src = img.dataset.smile == "true" ? "https://i.imgur.com/jgyJ7Oj.png" : "https://i.imgur.com/PqpOLwp.png";
}
<div>
    <img src="https://i.imgur.com/PqpOLwp.png" data-smile="false">
</div>

Hope that helps :)

CodePudding user response:

I tried to understand your question that you want the same goal but in an other code-way: you can use img.onclick = () => { ... }

here is example for that

let img = document.getElementById('img');
let isSmile
img.onclick = () => { 
  if(isSmile) {
    img.src = "https://i.imgur.com/PqpOLwp.png";
    isSmile = false
    }
  else {
    img.src = "https://i.imgur.com/jgyJ7Oj.png";
    isSmile = true
  }
}
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div>
            <img src="https://i.imgur.com/PqpOLwp.png" id="img">
        </div>
    </body>
</html>

CodePudding user response:

I propose a generic approach where one would toggle the image source between a primary (maybe the OP's "smile" state) and a secondary ("no smile") source.

An implementation then makes use of data-* global attributes like e.g. data-primary-toggle-src, data-secondary-toggle-src and maybe a data-toggle-state as well as of such an image element's related dataset property for reading the to be alternated image sources and writing the current toggle state (e.g. 'primary' versus 'secondary').

The generic approach and the encapsulated implementation makes this code re-usable (e.g. multiple time re-use within the same document or in other projects).

function initializeToggleImages() {
  function toggleImageStates({ currentTarget: imgNode }) {
    const { dataset, src: currentSrc } = imgNode;

    // read.
    const primarySrc = dataset.primaryToggleSrc;
    const secondarySrc = dataset.secondaryToggleSrc;

    const isPrimaryState = (primarySrc === currentSrc);

    // write / toggle.
    imgNode.src = isPrimaryState && secondarySrc || primarySrc;
    dataset.toggleState = isPrimaryState && 'secondary' || 'primary';

    console.log({ toggleState: dataset.toggleState });
  }
  document
    .querySelectorAll('img[data-secondary-toggle-src]')
    .forEach(imgNode =>
      imgNode.addEventListener('click', toggleImageStates)
    )
}
initializeToggleImages();
body { margin: 0; }
img[data-secondary-toggle-src] { width: 160px; height: 120px; cursor: pointer; }
.as-console-wrapper { min-height: 100%; left: auto!important; width: 50%; }
<img
  src="https://i.picsum.photos/id/312/3888/2592.jpg?hmac=Lk5n0q19XuicLgvYPdAr5iML0VbkEADyqgJoHH_5nAs"
  data-primary-toggle-src="https://i.picsum.photos/id/312/3888/2592.jpg?hmac=Lk5n0q19XuicLgvYPdAr5iML0VbkEADyqgJoHH_5nAs"
  data-secondary-toggle-src="https://i.picsum.photos/id/248/3872/2592.jpg?hmac=_F3LsKQyGyWnwQJogUtsd_wyx2YDYnYZ6VZmSMBCxNI"
  title="toggle me"
/>

<img
  src="https://i.picsum.photos/id/515/4585/3439.jpg?hmac=WSSTufs9yyQUM8j16-DUr6nfucMBKIw7XHyMruISqeQ"
  data-primary-toggle-src="https://i.picsum.photos/id/512/3434/4340.jpg?hmac=DMhjASC-MZzL9bg0VcfO7vXLZscfbcjNLm7Rosmo0iw"
  data-secondary-toggle-src="https://i.picsum.photos/id/515/4585/3439.jpg?hmac=WSSTufs9yyQUM8j16-DUr6nfucMBKIw7XHyMruISqeQ"
  title="toggle me"
/>

  • Related