Upon clicking a button, how do I fade the background so its translucent and show an image over the page

Let's assume I have a button with an image inside it. Upon clicking the button, I want the background to fade out and I want a different image (similar to the button image but more modified) to show in bigger proportions. I want the image to pop up in the centre of the website and I don't want it to take up the entire space of the website - showing the faded background.

P.S. - The button image and the modified image are in two different files, and upon clicking the button, the modified image is displayed. The button has the button image file displayed as an img inside it.

1 answer

  • answered 2022-01-13 11:05 A Haworth

    You could use the before and after pseudo elements on the button to hold the two images.

    This snippet puts the first image as the background to the before pseudo element and the enlarged one as the background to the after pseudo element.

    The after pseudo element has opacity 0 until the button is clicked and the before pseudo element gets opacity 0 when the button is clicked. And these are reversed when the button is clicked again for this demo - it depends on exactly what you want as to what Javascript you will want to put here.

    Just for the demo the change in position and the sizes are transitioned along with the opacities to get the fade effect. You could of course have the larger image shown instantly by having the transitions only on the opacities - it depends on what you need.

    button {
      left: 0;
      top: 0;
      width: 15vmin;
      height: 10vmin;
      position: relative;
      background-color: transparent;
      transition: 1s;
    }
    
    button::before,
    button::after {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      z-index: -1;
      background-size: cover;
      transition: 1s;
      opacity: 1;
    }
    
    button::before {
      background-image: url(https://picsum.photos/id/1015/300/300?grayscale);
    }
    
    button::after {
      background-image: url(https://picsum.photos/id/1015/300/300);
    }
    
    button::before,
    button.clicked::after {
      opacity: 1;
    }
    
    button.clicked::before {
      opacity: 0.5;
    }
    
    button::after {
      opacity: 0;
    }
    
    button.clicked::after {
      background-size: contain;
      background-position: center center;
      background-repeat: no-repeat;
      width: 50vw;
      height: 50vh;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    }
    
    button.clicked {
      left: 50vw;
      top: 50vh;
      transform: translate(-50%, -50%);
      width: 100vw;
      height: 100vh;
    }
    <button onclick="this.classList.toggle('clicked');"></button>

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum