Putting a CSS square above the image and then removing it using JavaScript

I am new to javascript, so please forgive me if this question is really basic. I have one problem with what I'm trying to do.

I have an image on the page.

I want to put a black box on top of the image (presumably using CSS), i.e. hide image.

Then, using JavaScript, when the mouse moves around the CSS black square, the black box disappears showing the image.

I know how to make fade out using JavaScript, but I can’t get the CSS field on top of the image ...

Thank you if you can help by telling me how to do this.

Notice that in my efforts I created a field using CSS and then added an image to the page, but the image just deleted the CSS field.

+3
source share
5 answers

I decided to add a black cover using JavaScript. This way, a user with JavaScript disabled will still see your image.

HTML

<div id="container">
   <img src="path/to/your/image.png" alt="Hello" />
</div>

CSS

#container {
   position: relative;   
}

#container div {
   width: 100%;
   height: 100%;
   position: absolute;
   top: 0;
   left: 0;
   background: #000;
}

JQuery

$(function() {
    var container = $('#container'),
        div = $('<div />').appendTo(container);

    container.hover(function() {
        div.fadeOut(500);
    }, function() {
        div.fadeIn(500);
    });
});

jsFiddle .

+4
source

You can try using z-index CSS. See here . Please note that position:absoluteis important.

Here is one way to do it. I think it might work.

  • Image at the bottom of the layer.
  • Box over image layer.
  • JS to delete a field.
+1
source

, , .

do-fade. .

jQuery, :

$(document).ready(function() {
    $("img.do-fade").each(function () {
        var t = $(this);
        var d = $('<div class="black-box"></div>').insertAfter(this);
        d.css({ width: t.width(), height: t.height(), top: t.position().top });
        d.bind("mouseenter", function() {
            $(this).fadeTo("normal", 0);
        }).bind("mouseleave", function() {
            $(this).fadeTo("fast", 1);
        });
    });
});
+1
source

I would suggest fading out the image on a div with a black background containing the image from the very beginning.

0
source

put the image in a div with:

background: black;

css for image (in normal condition):

visibility: hidden;

and with js, change the visibility of the image in case you want.

.. or you can try only css:

div.container{
    background: black;
}
image{
    visibility: hidden;
}
image:hover{
    visibility: visible;
}
0
source

All Articles