0

I am new to Jquery and Javascript. I want my code to play a sound when clicking anywhere in the document, and a different sound when double clicking on a .marker.

It works right now, but when I double click the marker it plays the .click function twice along with the double click function.

How do I prevent the .click from playing when I double click?

Here is my Jquery code:

$(document).ready(function () {

    $(document).click(function () {
        setTimeout(function () {
            let audio = document.createElement("audio");
            audio.src = "audio/click-audio.wav";
            audio.play();
        }, 700);
    });

    $('.marker').dblclick(function () {
        let audio = document.createElement("audio");
        audio.src = "audio/page-audio.wav";
        audio.play();
    });

});
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
  • Does this answer your question? [Prevent default single click event on double click on a link in HTML](https://stackoverflow.com/questions/48895168/prevent-default-single-click-event-on-double-click-on-a-link-in-html) – Pushprajsinh Chudasama Mar 05 '20 at 05:49

3 Answers3

0

Using event properties, you could achieve

$('marker').click(function(event) {
  if(!event.detail || event.detail == 1){
    // code here.
    // It will execute only once on multiple clicks
  }
});
joy08
  • 9,004
  • 8
  • 38
  • 73
0

Just check whether clicked element is .marker :

$(document).click(function(event) { 
      if($(event.target).is(".marker")) return ;
        setTimeout(function() {
            let audio = document.createElement("audio");
            audio.src = "audio/click-audio.wav"; 
            audio.play();}, 700);


    });
thingEvery
  • 3,368
  • 1
  • 19
  • 25
Ritesh Khandekar
  • 3,885
  • 3
  • 15
  • 30
0

The stopPropagation() method stops the bubbling of an event to parent elements, preventing any parent handlers from being notified of the event.

$(document).click(function () { 
        setTimeout(function() {
            let audio = document.createElement("audio");
            audio.src = "audio/click-audio.wav"; 
            audio.play();}, 700);


    });

    $('.marker').click(function (event) { 
        let audio = document.createElement("audio");
        audio.src = "audio/page-audio.wav"; 
        audio.play(); 
        event.stopPropagation();
    });

});

hope it will help you

rishi
  • 1