Complex JavaScript – Keep Code Clean

complex javascriptThere are standard coding practices to adhere to when coding more complex JavaScript. The underlying concept is to seperate JavaScript from the HTML document.

Look at this line of code for example.

<h1 id=”title” onclick=”alert(‘hello’);”>Hello</h1>

 

In this instance there is one bit of JavaScript after the onclick attribute. There certainly could be much more JavaScript after the onclick attribute, but that is considered bad form to write many lines of code for one attribute. There is a cleaner way to do it.

The <script> tag is used to import jQuery. A <script> tag is also used to call on custom code.

<script type=”text/javascript”>alert(‘Hello’);</script>

The above script has a type indicating that it is text consisting of JavaScript. Everything inside the script tags is the JavaScript.

Take one step further and put the JavaScript inside a function named sayHello().

function sayHello() {
++++alert(‘Hello’);
};

And one more step by simply placing the function inside the <script> tag.

<script type=”text/javascript”>
function sayHello() {
++++alert(‘Hello’);
};
</script>

 

This might have been lots of work for a simple JavaScript function, but consider if the function is 500 lines of JavaScript, and is easy to see why doing it this way makes sense.

Now you can look at everything in the context of a web page.

<head>
</head><body>
++<h1 id =”title” onclick=”sayHello()”>
++++Hello
++</h1>
</body>
<script type=”text/javascript”>
function sayHello() {
++++alert(‘Hello’);
};
</script>

This can be taken one step further with a separate JavaScript file. Similar to a CSS file, a JavaScript file can be used to affect multiple HTML pages.

To do this, paste all the JavaScript code in a separate file with a name like scripts.js. Do not include the <script> tags in this document. In the HTML files, simply link the JavaScript file with <script src="scripts.js"> </script>. The way JavaScript functions are invoked from HTML elements does not change.

Leave a Reply

Your email address will not be published. Required fields are marked *