How can I change the opacity of images using javascript and buttons?

Without changing the HTML, I need 3 buttons, one for each shape, and when I click the first button, I need the opacity of the second and third shapes to be 0%, and the first image to be 100%, and so on for the other two buttons.

body {
  font-family: Avenir, sans-serif;
}
h1 {
  text-align: center;
  font-weight: 100;
}
#works {
  display: flex;
}
#works figure {
  transition: 1s opacity;
}
#works figure img {
  width: 100%;
  margin-bottom: 1rem;
}
        
      

Run codeHide result


<!doctype html>
    <html lang=en>
    <head>
    <meta charset=utf-8>
    <title>Sculptors and Architects of the Italian Renaissance</title>

    </head>
    <body>
    <h1>Sculptors and Architects of the Italian Renaissance</h1>
    <div id="works">
        <figure data-artist="michelangelo">
        <img src="david.jpg" alt>
        <figcaption>Head of <i>David</i>, Michelangelo (c. 1501)</figcaption>
    </figure>

    <figure data-artist="donatello">
        <img src="david-plaster.jpg" alt>
        <figcaption>Detail from painted plaster replica of Donatello bronze <i>David</i> (c. 1430)</figcaption>
    </figure>

    <figure data-artist="brunelleschi">
        <img src="florence-cathedral.jpg" alt>
        <figcaption>Dome of Florence Cathedral by Filippo Brunelleschi (1436)</figcaption>
        </figure>
    </div>

    <div id="controls">
    <button id="button">Michelangelo</button>
    <button id="button2">Donatello</button>
    <button id="button3">Brunelleschi</button>
    </div>
      <script>

        </script>
    </body>
    </html>

      

+3


source to share


1 answer


made some changes:

<button id="michelangelo">Michelangelo</button>
<button id="donatello">Donatello</button>
<button id="brunelleschi">Brunelleschi</button>

      



Using jQuery:

$('button').click(function(e){
    e.preventDefault();
    $('figure').style.opacity = '0';
    $(`figure[data-artist="${$(this).attr('id')}"`).style.opacity = '1';
});

      

0


source







All Articles