3

I'm trying to make an image with area tags where I can click on each area and show an alert.

With both "tap & click" included, I can't seem to figure out how to avoid firing the event twice on desktop mode using a mouse click.

$(document).ready(function(e) {
    $('img[usemap]').something();

    $('area').on('tap click', function() {
        alert($(this).attr('alt'));
    });
});

I've searched several ways such as separating the events using Boolean, but they didn't really work as I'm really bad at javascript...

Please help me figure this out. Thank you very much!

Andy Lester
  • 91,102
  • 13
  • 100
  • 152
Peter W
  • 75
  • 1
  • 8
  • 1
    I made a jsfiddle that should have reproduced the error, and it doesn't: https://jsfiddle.net/s3m3x4ds/ My guess is you have the same code included twice on the page somehow, and it's binding two click events to the same element. – John Sparwasser Jun 22 '15 at 22:45
  • @JohnSparwasser Thanks! That's interesting. Why doesn't this fire twice but mine does :/ – Peter W Jun 22 '15 at 22:46
  • 1
    You could also just take out the tap to see if that is giving you the error. If it's still firing the events twice without the tap event bound, you know it's duplicated code, or something along those lines. – John Sparwasser Jun 22 '15 at 22:49
  • @JohnSparwasser tried taking out "tap" and leaving only "click", it fires only once without any error, but nor does "tap click" give me any error either, it just fires twice :/ I've gotta spend more time studying on javascript.. Thanks for the help! – Peter W Jun 22 '15 at 22:54

1 Answers1

3

You can try testing for window.ontouchstart and only binding the relevant event

$(document).ready(function(e) {
    $('img[usemap]').something();

    function clickArea(){
        alert($(this).attr('alt'));
    }

    if(typeof window.ontouchstart === 'undefined'){
        $('area').on('click', clickArea);
    } else{
        $('area').on('touchstart', clickArea);
    }
});
Kevin F
  • 2,836
  • 2
  • 16
  • 21
  • whoa it works beautifully! Big Thanks! will mark as answer after the countdown. – Peter W Jun 22 '15 at 22:45
  • 1
    This will cause problems on devices that have both a touch and a click interface. See here: [JavaScript touchend versus click dilemma](http://stackoverflow.com/questions/25572070/javascript-touchend-versus-click-dilemma/44060724#44060724) – Web_Designer May 19 '17 at 03:12