Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

background image event handler

If a HTML element (e.g. div) has a CSS background image is it possible to assign an event handler that is triggered when the user clicks on the background image, but not any other part of the element?

If so, a JQuery example would be much appreciated.

like image 935
Dónal Avatar asked Oct 09 '22 12:10

Dónal


2 Answers

While it's not possible to detect a click on the background image, you can use some clever JS and CSS wizardry and come up with a masking element over the background image like this: http://jsfiddle.net/ahmednuaman/75Rxu/, here's the code:

HTML:

<div id="bg_img_1"></div>
<div id="bg_img_2">
    <div id="hit"></div>
</div>

CSS:

div
{
    display: block;
    position: relative;
    width: 200px;
    height: 200px;
    background-repeat: no-repeat;
    background-position: center center;
}
#bg_img_1
{
    background-image: url('http://placekitten.com/100/100');   
}
#bg_img_2
{
    background-image: url('http://placekitten.com/100/100');   
}
#hit
{
    display: block;
    position: absolute;
    width: 100px;
    height: 100px;
    background: #000000;
    opacity: .3;
    margin: 50px;
}

JS:

function handleClick(e)
{
    console.log(e.target.id);
}

$( '#bg_img_1' ).click( handleClick );
$( '#hit' ).click( handleClick );
like image 173
Ahmed Nuaman Avatar answered Oct 13 '22 10:10

Ahmed Nuaman


I think there is a better and simple way to achieve this here is my solution

$(document).ready(function() {
$("*").click(function(event)
{
    if(event.target.nodeName == 'BODY')
    {
        alert('you have just clicked the body background');
    }
});
like image 40
user367864 Avatar answered Oct 13 '22 12:10

user367864