Search code examples
javascriptjqueryonclicktargetsaim

Shooting Targets: On mouse click -> Leave Bullet Hole.gif


I have a section on my website that has several aim targets for visitors click to shoot at. I am using cursor: crosshair for the section. I want to make it so that When my visitor clicks anywhere in the targets section I want to leave an animated bullet_hole.gif

I guess the command for the code would be within div container onmouse click create a div at the click Location and then delete the div after 5 seconds.

How do I write the javascript/jQuery code to do this?


Solution

  • To get the location of the click within a container you can get the offsetX and offsetY properties from the event object passed to the jQuery click handler. You can then create an absolutely positioned div at that position which contains the bullet hole image to be displayed. From there you can use a timer to remove that div after 5 seconds. Something like this:

    $('#target').click(function(e) {
        $('<div />').addClass('bullet-hole').css({
            top: e.offsetY - 5,
            left: e.offsetX - 5
        }).appendTo('#target');
        setTimeout(removeBulletHole, 5000);
    });
    
    function removeBulletHole() {
        $('#target .bullet-hole:not(:animated):first').fadeOut(function() {
            $(this).remove();
        });
    }
    

    Example fiddle