0

Hi, I'm new to JS:

<!doctype html>
<script type="text/javascript">
//JS start
function give_me_an_alertbox():
    alert("This is an alert box.");
//JS end
</script>
<a href="javascript: give_me_an_alertbox()">ALERT BOX!</a>

How come this code does not work!?
How do I refer to Javascript using href ?

4
Contributors
5
Replies
8
Views
5 Years
Discussion Span
Last Post by JorgeM
0

Your Javascript shows a bit of a Python influence. In Javascript you use curly braces to denote the beginning and end of a function body - not indentation. And there's no colon after the function signature.

0

Your code should be:

<!doctype html>
<script type="text/javascript">
//JS start
function give_me_an_alertbox()
    alert("This is an alert box.");
//JS end
</script>
<a href="javascript: give_me_an_alertbox()">ALERT BOX!</a>

Only the colon was taken out.

0

Hmm...I thought you had to put a { like this:

<!doctype html>
<script type="text/javascript">
//JS start
function give_me_an_alertbox() {
    alert("This is an alert box.")
}
//JS end
</script>
<a href="javascript: give_me_an_alertbox()">ALERT BOX!</a>

That also seems to work.

0

The braces are optional when the function only contains one statement. If you have more than one statement though, you need them - if you leave them off only the first statement will be interpreted as part of the function and the others will be outside of the function.

It is good style to always use the braces.

0

Just as an additional note, you may want to include the void() function to prevent the post back when using JavaScript in combinatino with links. for example:

<a href="JavaScript:void(0);give_me_an_alertbox()">ALERT BOX!</a>

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.