Click on an image to show a div

Asked

Viewed 2,693 times

0

My question is as follows, when you click on image 1, div 1 appears, but then when you click on image 2, div 1 disappears and div 2 appears, and then when you click on image 3 div 2 disappears and div appears.

How can I do that?

Thank you.

  • Depending on what you need to do, maybe what you are looking for is an Accordion. See example: https://jqueryui.com/accordion/

2 answers

2


Can do only with CSS, using the selector target:

div { display: none }         /* Por padrão, os divs iniciam ocultos. */
div:target { display: block } /* Exibe quando o elemento é alvo. */
<a href='#cachorro'>
  <img src='http://i.stack.imgur.com/qxjHV.jpg'/>
</a>
<a href='#gato'>
  <img src='http://i.stack.imgur.com/YbkW1.jpg'/>
</a>

<div id='cachorro'>
  <p>lorem cachorro lorem...</p>
</div>
<div id='gato'>
  <p>lorem gato lorem...</p>
</div>

  • In this case, how would you apply 5 images and 5 Divs? Thank you.

  • 1

    Creating a <a> (containing the image) for each of the Ivds, linking the href of the link with the id of the div.

  • Thanks, I got it right!

  • Now that I tried to apply to my example, the site got all fucked up.

  • What I’m talking about is that all Ivs get fucked up.

1

Hello, if you want to better manipulate the page objects you can use jquery, I made a basic example

<!DOCTYPE html>
     <html>
     <head>
     <meta charset="UTF-8">
     <title>slider</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <style>
        #div1 { background-color: yellow }
        #div2 { background-color: blue }
        #div3 { background-color: green }
    </style>
     <script>
        $(function(){
            $('#div1,#div2,#div3').css({'float':'left','margin-top':'300px'}).hide();
            $('#img1,#img2,#img3').css({'cursor':'pointer'});
            $('#img1').click(function(){
                $('#div1').fadeIn('slow');
                $('#div2,#div3').fadeOut('slow');
            });
            $('#img2').click(function(){
                $('#div2').fadeIn('slow');
                $('#div1,#div3').fadeOut('slow');
            });
            $('#img3').click(function(){
                $('#div3').fadeIn('slow');
                $('#div2,#div1').fadeOut('slow');
            });
        });
     </script>
     </head>

     <body>
         <img width="50" height="50" id="img1" border="1">
         <img width="50" height="50" id="img2" border="1">
         <img width="50" height="50" id="img3" border="1">

         <div id="div1">div1</div>
         <div id="div2">div2</div>
         <div id="div3">div3</div>
     </body>
     </html>

or only with css you define the object/class

div#img1:target { ..... }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.