When someone clicks on one of these images I would like that image to appear as the background image of div "slides", and am not sure what is going wrong. Maybe I am not using "this" properly.
function showslide() {
y = document.getElementById("slides");
y.style.display = "block";
z = this.src;
y.backgroundImage = 'url(' + z + ')';
}
<div id="slides">Div</div>
<div id="slidermenu">
<img class="slidermenuimage" src="https://placehold.co/600x400/red/white" onclick="showslide()"/><br>
<img class="slidermenuimage" src="https://placehold.co/600x400/orange/white" onclick="showslide()"/><br>
<img class="slidermenuimage" src="https://placehold.co/600x400/yellow/white" onclick="showslide()"/><br>
</div>
3
Answers
Instead of using this, pass event into your functions. Then use event.target
You also need to use y.style.backgroundImage You left out the .style
By default the slides div has 0px height, so you need to set a height to see the background image.
See my EDIT comments in the code snippet for specific edits.
Yes you are using
this
wrong, because you use inline event handlers which is not recommended. See the other answer for the inline handlingAlso the assignment of backgroundImage is missing
style.
Instead use addEventListener on the container so you can delegate
Event Delegation
Although it’s big in React, inline event handlers (or on-event handlers) are still discouraged. Use
addEventListener()
method.If you have multiple elements needing an event handler❇, add the event handler (via
addEventListener()
to an ancestor element they all have in common. That could bewindow
,document
,body
, etc. but it’s better if you choose the closest one to the elements you intend to interact with. In your particular layout that would be#slidermenu
(in Demo it’s renamed#image-menu
). See Example 1 below.Example 1
❇ event handler is a function that’s used to handle an event via
.eventListener()
, on-property, or on-event.When you write your event handler, you determine which elements will react to the event and exclude all other elements simply by not even mentioning them. To help you sort out the specific element the user interacted with (eg. "clicked"), use the event.target property. See Example 2 below.
Example 2
Demo