I am aiming to create a dropdown menu that when each item of the dropdown is clicked, it shows a different image above it, by replacing the one before. I have been using these pages as guidance:
The dropdown menu has nine options and the html looks like this:
<div class="dropdown">
<img id="a_features" src="a_features" style="display:none;"/>
<button onclick="myFunction()" class="dropbtn">Change in Audio Features Over Time</button>
<div id="myDropdown" class="dropdown-content">
<a onclick="danceability()">Danceability</a>
<a onclick="duration()">Duration</a>
<a onclick="energy()">Energy</a>
<a onclick="instrumentalness()">Instrumentalness</a>
<a onclick="liveness()">Liveness</a>
<a onclick="loudness()">Loudness</a>
<a onclick="speechiness()">Speechiness</a>
<a onclick="tempo()">Tempo</a>
<a onclick="valence()">Valence</a>
</div>
And one example of the functions I am using, they are all identical except for the image source, is this:
function danceability(){
var pic = "https://imgur.com/Ga5bnai"
document.getElementById('a_features').src = pic.replace('90x90', '225x225');
document.getElementById('a_features').style.display='block';
}
This setup works when I use the image used in the stack overflow example ("http://img.tesco.com/Groceries/pi/118/5000175411118/IDShot_90x90.jpg"), but fails when I try and link it to the images hosted on imgur. Is this an issue with the image source and, if so, how do I get around this?
To me it seems like the imgur link you're using (if it's the one you're actually using), (a) doesn't link to an image but to a webpage (b) does not include '90x90', so won't replace it with anything else. If you would replace the src with a link to an actual image it would probably work. Also, you can generalize the function. Instead of calling a different function on each item, you could call 1 function, and add the image src in a data-attribute, for instance:
<div id="myDropdown" class="dropdown-content">
<a data-image="https://imgur.com/Ga5bnai">Danceability</a>
<a data-image="https://imgur.com/35ewr">Duration</a>
<a data-image="https://imgur.com/fas353F">Energy</a>
<!-- ... -->
</div>
const image = document.getElementById('a_features');
const setImage = (element) => {
const src = element.dataset.image;
image.src = src.replace('90x90', '225x225');
image.style.display = 'block';
}
document.querySelectorAll('#myDropdown a').forEach((item) => {
item.addEventListener('click', () => setImage(item));
});
An example: https://codepen.io/dagropp/pen/WNZzaay