Now I wish to try to create an external JavaScript file. I think it would also be a good time to mention again I’m writing all my code just in Notepad – nothing fancy. Also, remember I’m following the W3Schools JavaScript course. I noticed that the code is written different when placing it in an external file:
function myFunction() {document.getElementById(“love”).style.width=”500px”;}
In Part 1 the code was written inside the file like so:
<div onclick=”document.getElementById(‘love’).style.width=’500px'”>
First, as you can see there is one less set of quotation marks. It appears the quotation marks at the start and end are no longer required. Second, now we are using a semi-colon at the end after the quotation marks. Last, we have the introduction of a ‘function myFunction’ feature.
I tested the ‘function myFunction” portion of the code, I wanted to know if the ‘myFunction‘ name (or any parts of it) was mandatory. I figured it wasn’t and replaced it with various text. The code executed just fine with any name just as I suspected – but note I didn’t test it with a name with any numbers or symbols in it, just letters). So with this knowledge let’s change the name:
function whateverdude() {document.getElementById(“love”).style.width=”500px”;}
To create an external JavaScript file I put the above code in a notepad file and named it love.js. Next I created the HTML file. The HTML is almost the same from Part I, you create your div, p, span, etc. and give it the associated id, in this case it would ‘love.’
HTML:
<div id=”love” style=”width: 250px; border: 2px solid green; padding: 24px;”>
Jason Learns Code.
</div>
Now you need to add a link to your Javascript – otherwise how is the code going to find the location of “love” assigned to the id in the div? So you must add the following to your HTML:
<script src=”love.js”></script>
Note the external script code can be placed in either the <head> or the <body>.
Next, you have to add a button – I’m sure there are other ways to ‘activate’ the JavaScript beyond having the User click a button (onclick), but for now that is all that has been demonstrated.
HTML:
<button type=”button” onclick=”whateverdude()”>Push!</button>
You can see this button’s ‘onclick’ feature is ‘calling’ the ‘whateverdude’ code via our “external ‘love’ JavaScript file. So if you click the button the width of the div should change from 250px to 500px.
You can view the results here.