1 if (document.getElementById) {
2 document.write(
3 '<style type="text/css" media="screen">
4 #element1, .element2 {display:none;}
5 </style>'
6 );
7 }
I get "Uncaught SyntaxError: Unexpected token ILLEGAL" on line 3. This is probably soo easy for you guys, but I just started with JS and like always - it's a whole new language.
I could use 2 kinds of advice if they are different..
I know how to link .js, don't worry about that.
For the record, this is intended to be in < head > and to hide some html elements before they are fully loaded if Im not mistaken. Experts, feel free to confirm this or give me a better solution if there is any, thank you!
In JavaScript, strings cannot be broken up into multiple lines. The new line character is not a valid string character. You will have to close the string on each line and add the string concatenation operator after each line that is continued on the next line (or before each line that is a continuation of the previous line, like so:
if (document.getElementById)
{
document.write(
'<style type="text/css" media="screen">' +
'#element1, .element2 {display:none;}'
+ '</style>');
}
This will get rid of the error, but it will not achieve the desired effect of hiding elements. document.write
automatically calls document.open() if an HTML document has already been opened (which it has, if the script is executing.) document.open
will wipe out the contents of the page, including the script that contains that code. You will be left with a blank page.
As @Chris says, you can include script tags in the output of a php script simply by writing the script outside of the php parsing context. i.e.
?>
<head>
<!-- other stuff -->
<script type="text/javascript">// type="text/javascript" is only needed for browser versions that do not support HTML5
// place code here
</script>
<!-- other stuff -->
</head>
<?php
On the other hand, if you wish to include a separate, external JavaScript file, replace that script tag in the code snippet above with
<script src="[absolute or relative path to script]" type="text/javascript">
</script>
Note that script tags are not self-closing, so even though this script tag has no contents, you cannot use the self closing tag syntax, as in <script ... />
As for the problem of how to handle the flickering problem, this Stack Overflow post may be helpful: