Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

131
Visualizações
JavaScript function in HTML

I have an HTML page with 5 button elements button 1, button 2, button 3, button 4 and button 5.

I also have an image element dog1.jpg.

What i need to do is when I click on button 1 I need it to display dog1.jpg when I click on button 2 I need it to display dog2.jpg and so on for the 5 buttons.

I'm having trouble writing a function to do this, so far I just have the 5 buttons written.

Can someone please help me create a function im completely stuck.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

pass the btnName onclick to chnageImg function shown below

   function changeImg(btnName) {
            var image = document.getElementById('myImg');
            switch(btnName){
           case "btn1":image.src="dog1.jpg";break;
           case "btn2":image.src="dog2.jpg";break;
           case "btn3":image.src="dog3.jpg";break;
           case "btn4":image.src="dog4.jpg";break;
           case "btn5":image.src="dog5.jpg";break;
           default: break;
        }
        }
about 4 years ago · Juan Pablo Isaza Relatório

0

The modern approach is to put the buttons in a container and use event delegation to add one listener to the container, and have that capture events from its child elements as they "bubble up" the DOM.

That listener will call a handler function when any button is clicked.

Add data attributes to each button so they can be identified, and the correct image retrieved.

Links to documentation of the concepts covered here are at the bottom of the answer.

// Cache your elements
const buttons = document.querySelector('.buttons');
const img = document.querySelector('img');

// Add a listener to the container
buttons.addEventListener('click', handleClick, false);

function handleClick(e) {

  // If the element that was clicked on
  // was a button
  if (e.target.matches('button')) {

    // Destructure the id from the dataset
    const { id } = e.target.dataset;

    // Create a filename from the id
    // Here I've used a template string
    const filename = `dog${id}.jpg`;

    // Finally add the filename to the image src attribute
    // (here I'm using a dummy image to get the
    // example to work)
    img.src = `https://dummyimage.com/100x100/efefef/0011ff&text=${filename}`;
  }
}
img { margin-top: 1em; }
<div class="buttons">
  <button data-id="1">Dog 1</button>
  <button data-id="2">Dog 2</button>
  <button data-id="3">Dog 3</button>
  <button data-id="4">Dog 4</button>
  <button data-id="5">Dog 5</button>
</div>
<img />

Addition documentation

  • Data attributes

  • Destructuring assignment

  • https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

  • matches

  • querySelector

  • Template/string literals

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda