treehouse : what would you like to learn today?
Web Design Web Development iOS Development

[Solved] Hover over text to trigger opacity change to images

  • Hello

    So basically I want the list of anchor tags to trigger an opacity change to a specific image below, at the same time as changing colour of the text when hovered over.

    I'm a little rusty and not quite sure how to approach this.

    Any help would be much appreciated.

    image

  • You want to use CSS only or you happy with using a bit of javascript

  • As long as it works, I don't really mind.

  • I think this is something forJavascript.

    If you were clicking you could use the :target pseudo selector but with :hover I don't think you can affect two elements like that unless they have the same parent element...but I'll have a think.

  • <html>
      <body>
        <div class="piclinks">
        <a href="" class="linkA">Link A</a>
        <a href="" class="linkB">Link B</a>
        </div>
        <img src="" alt="placeholder" class="linkA"/>
        <img src="" alt="placeholder" class="linkB"/>
      </body>
    </html>
    

    Css

      .hovered {
          opacity: 0.5; 
      }
    

    Jquery

      $(document).ready(function(){
          $('.piclinks a').hover(
              function () {
                      $('img.'+$(this).attr('class')).addClass('hovered');
              },
              function () { 
                  $('img.'+$(this).attr('class')).removeClass('hovered');
              });
          });
    

    thats a bit hacky, but should give u a pointer in the right direction

  • Hey, that worked!

    I still have a problem though. I should have mentioned this before, but the images are set to a low opacity to start with. I need the hover to change the image from 0.3 to 1.0.

  • just change the opacity value in the code above from 0.5 to 1

  • I don't think that would work. Your code is good if I want to lower the opacity of an image, but I'm wanting to up the opacity. If I was to change the value from 0.5 to 1, then the hover will have no effect, because the image is at 1 to start with.

    See the problem?

  • .initialopacity {
      opacity: whatever you want the default opacity to be
    }
    
    <img src="" alt="placeholder" class="initialopacity linkA"/>
    

    when the jquery hover triggers it add's the hovered class to the img tag overriding any opacity set before (unless it has a higher specificity)

  • Wow, that's cool, I never knew you could do that.

    Thank you for your help.