user2100672
user2100672

Reputation:

Adding and removing divs on hover

I'm currently creating a gallery and would like to add a white tint to my images when a user hovers over an image. I've managed to add the .view-me div on hover but I can't work out how to remove it. I've tried .remove() to no success - any ideas?

JS

$(document).ready(function() {
    $('.photo-block').hover(function() {
        $(this).append("<div class='view-me' id='view-me'></div>");
        $(this).find("#view-me:last").remove();
    });
});

HTML

 <div class="grid">
     <div class="photo-block"></div>
     <div class="photo-block"></div>
     <div class="photo-block"></div>
     <div class="photo-block"></div>
     <div class="photo-block"></div>
 </div>

JSFiddle

Upvotes: 1

Views: 100

Answers (5)

The Blue Dog
The Blue Dog

Reputation: 2475

The CSS version as per my comment.

HTML:

<div class="grid">
    <div class="photo-block">
        <img src="xyz.jpg">
    </div>
</div>

CSS:

.grid{
    background-color:#f00;
}
.photo-block{
    background-color:#fff;
}
.photo-block img:hover{
    opacity:0.4;
}

Upvotes: 1

Khurram Hassan
Khurram Hassan

Reputation: 1544

I have modified the jQuery script to:

$(document).ready(function () {
    $('.photo-block').hover(function () {
        $(this).append("<div class='view-me' id='view-me'></div>");
    }, function () {
        $(this).find("#view-me:last").remove();
    });
});

You were adding and then removing the div on the same event. I have modified it to add the div on hover and remove it on hover out

You can check your JSFiddle example as well I have modified it.

Upvotes: 1

Ani
Ani

Reputation: 4523

Here you go:

http://jsfiddle.net/gmcPW/4/

$(document).ready(function() {
   $('.photo-block').hover(function() {
    $( this ).append( $( "<div class='view-me'></div>" ) );
    }, function() {
         $( this ).find( ".view-me:last" ).remove();
    }
  );

});

Upvotes: 1

brouxhaha
brouxhaha

Reputation: 4093

Using css: Demo

html:

<div class="photo-block">
     <div class="overlay"></div>
     <img src="http://placekitten.com/400/400">
 </div>

css:

.photo-block {
    position: relative;
}

 .overlay {
     width: 100%;
     height: 100%;
     position: absolute;
     right: 0;
     left: 0;
     top: 0;
     bottom: 0;
     background: rgba(255,255,255, 0.5);
     display: none;
 }

 .photo-block:hover .overlay {
     display: block;
 }

Upvotes: 2

sul4bh
sul4bh

Reputation: 636

Quick fix:

$(document).ready(function() {
    $('.photo-block').hover(function() {
        $('#view-me').remove();
        $(this).append("<div class='view-me' id='view-me'></div>");
    });
});

Upvotes: 3

Related Questions