0

// this is all i have
function myFunction() {

  var index = document.getElementById('concier').style.zIndex = 0;
  var foto = document.getElementById('foto').src = "queen2.png";

  return index + foto;
  
}
// i want this when te button is pressed again

var index2 = document.getElementById('concier').style.zIndex = -1;
var foto2 = document.getElementById('foto').src = "queen.png";

return index2 + foto2;

What I want is to press the button and change an image of a div but when I press the button again, go back to the original image. I am using HTML and Javascript.

  • Welcome to SO. You might find reading the site [help section](https://stackoverflow.com/help) useful when it comes to [asking a good question](https://stackoverflow.com/help/how-to-ask). To get the best answers to your question we like to see a) that you've attempted to solve the problem yourself first, and b) used a [mcve] to narrow down the problem. [Here's a question checklist you might find useful.](https://meta.stackoverflow.com/questions/260648/stack-overflow-question-checklist). – Andy Jan 11 '19 at 23:34
  • This should get you started: [Programmatically change the src of an img tag](https://stackoverflow.com/questions/11722400/programmatically-change-the-src-of-an-img-tag). Definitely check out the links posted in the comment from @Andy and next time you might get a more specific answer. – benvc Jan 11 '19 at 23:41

2 Answers2

0

You can use boolean variable and simple if statement for that

// global javascript variable
var flag =  true;

function myFunction() {
  var imgName = "";
  var zIndexVal = 0;
  if (flag) {
     imgName = "queen.png";
     zIndexVal = -1;
  } else {
     imgName = "queen2.png";
     zIndexVal = 0;
  }
  flag = !flag;
  var index = document.getElementById('concier').style.zIndex = zIndexVal;
  var foto = document.getElementById('foto').src = imgName;

  return index + foto;  
}
Amita Patil
  • 1,310
  • 2
  • 14
  • 22
0

This is a simple way to do it. But not the smartest way.

    var btn = document.getElementById("btn"); //Replace this with your button id
    var img = document.getElementById('img'); // Replace this with your img id
    var i = 0;

    btn.onclick = function(){
        if( i==0 ){
           img.src="two.jpg"; // Second Image
           i=1;
        }
       else if( i==1 ){
          img.src="one.jpg" // Back to first Image
          i=0;
       }
    }

The html will look like this , You can change this to your HTML code

<img src="one.jpg" alt="" id="img"> //The First loaded image
<button id="btn">Add</button> // Button to toggle between them.

Hope this helps.

Thanveer Shah
  • 3,250
  • 2
  • 15
  • 31