Home > Software design >  can someone help me with a function that clicks on a button and gets the right photo ( berlin button
can someone help me with a function that clicks on a button and gets the right photo ( berlin button

Time:09-11

so i have this code

<div >
          <h1>PICK YOUR FAVOURITE</h1>
          <p>Select the place you want to get a ticket</p>
          <button  id="berlin">BERLIN</button>
          <button  id="netherlands">NETHERLANDS</button>
          <button  id="sweden">SWEDEN</button>
          <button  id="italy">ITALY</button>
        </div>

and i have right this code in js for selecting a button and a get a border

for (let i = 0; i < btnPlaces.length; i  ) {
  btnPlaces[i].addEventListener("click", function (e) {
    let prevBtn = document.querySelector(".checked");
    console.log(prevBtn);
    if (prevBtn) {
      prevBtn.classList.remove("checked");
      e.target.classList.add("checked");
    } else {
      e.target.classList.add("checked");
    }
  });
}

css code

.checked {
  border: 3px solid rgb(34, 34, 34);
}

now i want to make or add to the function , the ability to show different photos based on the buttons to a div. lets call it (col-1)

for example i click berlin button and in div col-1 it shows berlin.jpg but when i click sweden it will show sweden and not berlin

CodePudding user response:

So assuming the id of each button is associated with the picture name you can simply do something like this with js:

document.querySelector('.place-container').addEventListener('click', e => {
  if (e.target.classList.contains('btn-places')) {    
    var img = document.getElementById("thePicture");
    img.src = 'img/'   e.target.id   '.jpg';
  }
});

If its not associated with the ID but the innerHTML of the button then replace

img.src = 'img/' e.target.id '.jpg'; with

img.src = 'img/' e.target.innerHTML '.jpg';

Then you said you had something like this in your html with a div with id col-1 so you need to add an img in there where you will edit the src with the js code above:

<div id="col-1">
<img id="thePicture" src="">
</div>

Here's a working example (you can right click and inspect the picture to see that the filepath is indeed updating.)

document.querySelector('.place-container').addEventListener('click', e => {
  if (e.target.classList.contains('btn-places')) {    
    var img = document.getElementById("thePicture");
    img.src = 'img/'   e.target.id   '.jpg';
  }
});
<div  id="piccon">
          <h1>PICK YOUR FAVOURITE</h1>
          <p>Select the place you want to get a ticket</p>
          <button   id="berlin">BERLIN</button>
          <button   id="netherlands">NETHERLANDS</button>
          <button   id="sweden">SWEDEN</button>
          <button   id="italy">ITALY</button>
        </div>

<div id="col-1">
<img id="thePicture" src="">
</div>

  • Related