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
  • 11,885
  • 5
  • 66
  • 81
  • 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) – Bhavik Kalariya 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
  • 7,650
  • 5
  • 32
  • 63
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,324
  • 1
  • 18
  • 25
Ritesh Khandekar
  • 3,767
  • 3
  • 13
  • 29
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