Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 239
Amit Joki Avatar asked Mar 30 '14 15:03

Amit Joki


People also ask

Does alert stop execution?

One of the nice things about the built-in JavaScript alert is that - unlike virtually anything else in JavaScript - it's synchronous. It's completely blocking, and no other code will execute until it's been dismissed.

What happens when JavaScript runs the alert () function?

One useful function that's native to JavaScript is the alert() function. This function will display text in a dialog box that pops up on the screen.

Why alert function is not working in JavaScript?

The reason alert() does not work is because previously you have checked "prevent this page from creating additional dialoug" checkbox.

What is the function alert () used for?

The alert() method is used to show an alert box on the browser window with some message or warning. We can use it as a message or as a warning for the user.


2 Answers

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.

like image 64
Quentin Avatar answered Sep 21 '22 07:09

Quentin


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.

like image 36
Charlie74 Avatar answered Sep 18 '22 07:09

Charlie74