Amit Joki
Amit Joki

Reputation: 59232

why does alert() break code execution?

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?

Upvotes: 13

Views: 5906

Answers (4)

Charlie74
Charlie74

Reputation: 2903

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.

Upvotes: 3

Daniel Bejan
Daniel Bejan

Reputation: 1468

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...

Upvotes: 1

Quentin
Quentin

Reputation: 943185

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.

Upvotes: 10

John Koerner
John Koerner

Reputation: 38079

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.

Upvotes: 1

Related Questions