Help for Image Gallery : Event handler not working

Hi,

I am trying to replicate the image gallery as shown in -

The button toggles from dark to light and adds the opacity class to the targeted div but does not toggle from light to dark and also doesn’t add the opacity-1 class. Can you please tell why it is happening this way? and how can i correct this?

Here is my code -

https://codepen.io/harshitbadolla/pen/LYGovKw

that very wierd the button become unclickable i tried to remove the opacity and use any other property like background-color and it work fine

i think the opacity has some effect other than the color transparent

i fixed your issue by adding the following to your button
z-index : 2;
by the way you have a missing ; at the end of this line
btn.textContent = ‘Lighten’

hope that help

hello @chrisdavidmills could you give us a hand here :wink:

have a nice day both of you

1 Like

This is indeed due to another side effect of opacity — elements it is applied to create a new stacking context, which is part of the system by which the browser decides which elements are drawn on top of which other elements (also affected by positioning, and a bunch of other things). So applying opacity to an element can cause unintended layout effects.

Read this article to learn more: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context

I fixed your example by updating the markup like this:

<div class="main-img">
    <button>Darken</button>
   <img src="https://source.unsplash.com/random" alt="">   
</div>

But I can’t really explain explain why :wink:

I think it is something to do with the fact that originally, the button was separate from the <div>, and applying opacity to it caused it to go into a separate stacking context, which then sat behind the <div>, making it unclickable. The <div> is later in the source order, so sits on top.

When it is inside the <div>, it will go into a separate stacking context, but this is inside the <div>s parent sacking context and so will sit on top of it.

2 Likes

thanks a lot @chrisdavidmills that really help

Thanks a lot @chrisdavidmills @justsomeone

you welcome :slight_smile: