views:

161

answers:

6
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head>
<title>Login</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">alert("Hola amigo")</script>
</head>
<body>

 --I still want to see the following-- >>
<p>Lorem ipsum</p>

</body>
</html>

Why does it terminate everything that follows? I I thought it wouldnt if you had it inside <head>. I dont like having it in the bottom (after /html). Whats the problem?

+5  A: 

What you probably want to do is define it as a function, and then call that function from the onLoad attribute of the body tag. (Or just put your alert call in the onLoad attribute in the first place.)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head>
<title>Login</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function foo() {
    alert("Hola amigo");
}
</script>
</head>
<body onLoad="javascript:foo()">

 --I still want to see the following-- >>
<p>Lorem ipsum</p>

</body>
</html>
Amber
You really don't need "javascript:" prefix in onload attribute.
kangax
A: 

I pasted the HTML in an page, and I am able to see the HTML after the alert. Which browser are you using?

Kirtan
You are right. I too had no problem in viewing the content.
rahul
The same happened to me. I assume you put the comment in After pasting it here to demonstrate what functionality you expect. CMS and TT are correct in why your alert does not work correctly.In future, when pasting a snippet, paste it as-is.
Russell
+3  A: 

That happens because the alert executes immediately when the head it's parsed, alert blocks parsing, so the content of the body haven't yet been loaded.

Execute your alert when the window has been loaded (window.onload event):

window.onload = function () {
  alert("Hola amigo");
}
CMS
+2  A: 

alert() blocks the UI thread (in other words - it's modal) until the user confirms the dialog. Nothing is supposed to happen on the page until the dialog is closed.

Tsvetomir Tsonev
A: 

Java script is a interpreter language or in other word read the script or execute the script in line by line manner . So in your case when it comes to alert [Which is Model window: disable everything behind it to prevent any user action]. It waits for user action then only it will read further script rty

rty
A: 

try this:

<script type="text/javascript"> //<![CDATA[ //Javascript Alert alert("Put your message here"); //]]> </script>

it doesn't matter where you put this. But if you want it to appear first, put it at the top of your script and at the bottom to appear last

somescriptguy