Вопрос

I have a div that looks like the following:

<div class="row-fluid product-to-be-categorized" data-id="584472"><img src="http://origincache-prn.fbcdn.net/10311205_575850285866660_368389950_a.jpg"></div>

I wanted such that when the div is clicked then it adds an semi-black-transparant overlay in front of the div, so the picture is covered with this transparant layer in front of it.

I have the following click handler:

  $('.product-to-be-categorized').on('click', function(event) {

                });

but I am unsure on what is the quickest and simplest way to do this

Это было полезно?

Решение

Simplest way would be to add a class with a pseudo element to the div on the click event.

DEMO

CSS :

.product-to-be-categorized {
    position:relative;
    width:50%
}
.product-to-be-categorized img {
    display:block;
    width:100%;
}
.overlay:before {
    content:'';
    position:absolute;
    width:100%;
    height:100%;
    background: rgba(0, 0, 0, 0.5);
}

jQuery :

$('.product-to-be-categorized').click('click', function (event) {
    $(this).addClass('overlay');
});

(if you need to toggle the overlay, just replace ".addClass" by ".toggleClass" in jQuery code)

Другие советы

Firstly, in the click handler you can append a div to the container:

$('.product-to-be-categorized').on('click', function(event) {
    $('<div />').addClass('overlay').appendTo(this);
});

Which has the following CSS:

.product-to-be-categorized {
    position: relative;
    /* other styling... */
}
.overlay {
    position: absolute;
    top: 0;
    right: 0;
    left: 0;
    bottom: 0;
    background-color: #000;
    opacity: 0.5;
}

Example fiddle

You can also make the overlay togglable by checking for its existance and removing:

$('.product-to-be-categorized').on('click', function(event) {
    if ($('.overlay', this).length) {
        $('.overlay', this).remove();
    }
    else {
        $('<div />').addClass('overlay').appendTo(this);
    }
});

Example fiddle

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top