Background Image Event Handler

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

If so, then a jQuery example will be considered.

+5
source share
3 answers

While it is not possible to detect a click on the background image, you can use some smart JS and CSS wizardry and come up with a masking element over the background image as follows: http://jsfiddle.net/ahmednuaman/75Rxu/ , here is 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 );
+2
source

, ,

$(document).ready(function() {
$("*").click(function(event)
{
    if(event.target.nodeName == 'BODY')
    {
        alert('you have just clicked the body background');
    }
});
+2

Here is a very simple code that works only with the axis xto show it by injecting an element imgwith the url value of the background image as srcwell as determining the height and width of the background image to calculate if a click has occurred on the background image or not.

This code needs tons of improvement. It does not work in the axis y. Also not involved background-positionand background-size. But it’s easy to add these futures.

Here is the fiddle :

And here is the jQuery code:

$('#d').bind('click', function(e){
    var d = $(this),
        bg = {};
    //insert an image to detect background-image image size
    $('body').append(
        $('<img/>').attr('src',
                   d.css('background-image').split('(')[1].split(')')[0]
    ).attr('class', 'testImage'));
    bg.h = $('.testImage').height();
    bg.w = $('.testImage').width();
   console.log(bg, e.offsetX, $('.testImage').width());

    if(e.offsetX >  $('.testImage').width()){
        $('#l').text('it was NOT on background-image');
    }
    else{
        $('#l').text('it was on background-image');
    }
   $('.testImage').hide();
})
0
source

All Articles