Question

When we use alert(), some times the code breaks.

For example:

HTML:

<span>Hi</span>

Javascript:

$(document).ready(function () {

    $("span").dblclick(function () {
        alert("b");
    });
    $("span").click(function () {
        alert("a");
    });

});

The alert("b") doesn't even show up.

But if we change both the alert() to console.log, it is logged.

Alert Demo & console.log Demo

So, what's happening?

Was it helpful?

Solution

alert opens a model dialogue. When it is open, you can't interact with any part of the page except the alert itself.

Since you can't interact with the page, the second half of the double click can't reach the span, so the double click event won't fire.

OTHER TIPS

Using alert() stops all code execution. It would be impossible to capture a double-click if you are already capturing the single click on stopping code execution.

To demonstrate, I've commented out the alert for the single click in your fiddle. You can see HERE that the alert now happens on the double click.

Because you are catching the first click and showing an alert. The second click doesn't get caught because the alert now has the focus.

If you log to the console, then both clicks get caught and you will notice that "a" gets logged twice.

There are a few functions that stop the code from running when they are called. This are called synchronous functions causing a pause in the code until you click OK. alert() is synchronous and so is prompt().This causes the click event to take place and pauses code from running so no more double click event takes place...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top