As you should have read by now, Javascript is always contained within <script> tags on the page. There's no quick and easy php way of doing <? to get around it, you're going to have to start your script with either <script> or <script type="text/javascript">, and end it with </script>. You're not allowed to have any </script> or <script>'s inside your code, so you're only declaring it's a script once.
Good Coding<script type="text/javascript">
if(DoSomething){
something();
};
</script>
Bad Codingif(DoSomething){
<script type="text/javascript">
something();
</script>
Worse Coding<script type="text/javascript">
if(DoSomething){
<script type="text/javascript">
something();
</script>
};
</script>
The first
Bad Coding will run, it will not do the if statement, but it will not error, since everything in the script if proper Javascript. The
Worse Coding will see the second <script> tag and just exit out, giving you an error in your browser.
This leads to the error consoles that are on your browsers. All browsers have them. It lets you check the errors you have on the page your viewing.
With
Internet Explorer you will get a a message at the bottom left corner of your browser, saying that there are errors on the page.
With
FireFox, you can go to Tools >> Error Console.
If you double click on the IE icon, you'll get up a message box, and you can cycle through the errors on the page. The FireFox dialog generally gives you more (and better) information about the error you're receiving, and you can also click the error to see the line that it's erroring out on. Very useful.
Now, say we have this:
<script type="text/javascript">
someError();
</script>
All we did was call a function to start, but if that is all you have, you will get an error saying that someError is not a function. So, to make the function, you would do this:
<script type="text/javascript">
function someError(){
//Do something here
};
</script>
More on Functions later.
Last thing for this tutorial, a bit of javascript etiquette when you're writing.
<script type="text/javascript">
if(Statement){
doSomething();
}else{
doSomethingElse();
}
</script>
gives exactly the same output as:
<script type="text/javascript">if(Statement) doSomething() else doSomethingElse </script>
But I know which one i'd rather read. Break up your code on new lines, your code should have the if statement on one line, with the { at the end of it. The else statement should be on one line with a } before it and { after, and the final end of the if statement on its own line. You don't always need an else, but put the last } on it's own line. It's just easier to read, and for the purposes of this tutoring group, it's the style we're going to be using!