Member Avatar for HTMLperson5

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 ?

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.

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.

Member Avatar for HTMLperson5

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.

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.

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>

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.