-1

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?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Shen Hui Zhang
  • 23
  • 1
  • 10

1 Answers1

2

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

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • I copied your code and it doesn't work. I copied the .bullet-hole style and pasted it in my css stylesheet I copied the javascript and pasted it in my header.php Inside tags I changed #target to #workcontainer Which is the #DIV id - I want the bullet holes in and it still does not work on my website. I am not sure why www.prismasites.com Scroll down until you see the targets – Shen Hui Zhang Dec 21 '15 at 03:43