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.
CodePudding user response:
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;
}
}
CodePudding user response:
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 >
<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