Wednesday, August 26, 2015

External CSS & JS Files

How would you reference a Javascript file or a CSS file in your html code? That is include the files in your code, such that you can reference them?

HTML File:

<!doctype html>
<html>
 <link rel='stylesheet' type='text/css' href='../styles.css'>
 <script type='text/javascript' src='byid.js'></script>
 <h1>What can javascript do?</h1>
 <button id='mybtn' onclick='changeText();'>Click Me!</button>
</html>

JS file:

function changeText() {
  var btn = document.getElementById('mybtn');
  btn.innerHTML = ('Hello Javascript' == btn.innerHTML) 
        ? 'Click Me!': 'Hello Javascript';
}

Whats important?

The src for script tag is mandatory for including the Javascript file. The parameter type, language for script tag are optional.

And <script> needs to be closed with a </script>. If you try to use <script type='text/javascript' src='byid.js'/>, then the code won't work.

For including the css file using the link tag, the rel parameter and href parameter are mandatory. The rest are optional.

No comments:

Post a Comment