Stack Juice
Stack Juice

Reputation: 137

How can I change the opacity of everything but the element I'm hovering over in jQuery?

I am trying to have people highlight over a laptop image and once they do so, I want everything but the laptop image I'm hovering over to ease into a black opacity color.

This is the code I have so far which makes everything in the body to change opacity:

$(document).ready(function () {
    $(".laptop_img").mouseenter(function() {
        console.log("Mouse over laptop");
        $("body").css("opacity", "0.5");
    });

    $(".laptop_img").mouseleave(function() {
        console.log("Mouse leaves laptop");
        $("body").css("opacity", "1");
    });
});

Upvotes: 1

Views: 1308

Answers (3)

Angivare
Angivare

Reputation: 476

I think an easier way to achieve this would be to create a fixed black semi-transparent element that is the size of the window, on top of everything, make it hidden by default and show it whenever the mouse hovers laptop_img.

You would also have to handle the hovered element's z-index so that it would appear on top of your black element.

Demo on JSFiddle: http://jsfiddle.net/edc642pz/2/

Upvotes: 2

Michał Kutra
Michał Kutra

Reputation: 1202

There are two ways to get what You want:

1/ You need to have these two compontents in separate container. For example

<div id="div-with-opacity" style="opacity:.7">
      everything what goes here will has opacity also
   </div>
   <img src="path-to-image" alt="" id="this-image-has-no-opacity"/>

2/ Just use rgba(0,0,0,.7) color as a background of layer. You can have elements inside div with this background and it's not affect these elements.

Upvotes: 0

shershen
shershen

Reputation: 9993

opacity CSS property applies to all the children of the element so if you do it on body then you img tag will have opacity:0.5 too.

So better solution could be add/show dynamically a div witch will be covering all body except the your image.

Upvotes: 0

Related Questions