Where to Discuss?

Local Group

Preface

Goal: Explain where to put Javascript also unobtrusive Javascript

Most developer these days know complex javascript framework. Beginner who step in must know about the basic, the unobstrusive javascript. I use no javascript framework, so that everyone can enjoy this beginner example.

Three Places

This article also explain where to put javascript:

  1. Oldschool Inline
  2. Internal Code
  3. External File

Where to Put Javascript?

Source Examples

You can obtain source examples here:


Example Case

Consider continue from our previous example.

Oldschool Example

The old school javascript might looks like these below. The javascript is attached on an event in a tag. In this case the onclick event.

    <div class="panel red display-container">
      <span onclick="this.parentElement.style.display='none'"
            class="button large display-topright">&times;</span>
      <p><strong>Danger!</strong>:
        Red light indicates door a secured.</p>
    </div>

The early html document in 90s use inline stylesheet.

onclick="this.parentElement.style.display='none'"

Now you can click each alert box, and the clicked box will be vanished.

Javascript: Oldschool Inline

This looks ugly, I know, because the javascript code is obstrusively written inside a tag. This method tends to be error prone, while it comes to complex javascript response. That is why we need to find other way.

Skeleton

Usually, your HTML5 document, have skeleton like this below:

<!DOCTYPE html>
<html>
<head>
  <title>...</title>
  <style>
    ...
  </style>
  <script>
      ...
  </script>
</head>
<body>
    ...
</body>
</html>

Let’s apply the javascript there.

Unobtrusive Javascript Event

We can rewrite the onclick event above as below code. Don’t get intimidate by this long code. This will be clearer soon.

<body>
  <div class="container">
    ...
  </div>
  <script>
    var alertButtons = document.getElementsByClassName("dismissable");
    
    for (var i=0; i < alertButtons.length; i++) {
      alertButtons[i].onclick = function() {
        this.parentElement.style.display='none';
        return false;
      };
    };
  </script>
</body>

We require a class to identify the DOM (domain object model). Let’s name it dismissible, and put on each span tag.

<body>
  <div class="container">

    <h2>Relationship Alerts</h2>
    <p>To close the alerts, click on the X in the upper right corner:</p>

    <div class="panel red display-container">
      <span class="dismissable button large display-topright">&times;</span>
      <p><strong>Danger!</strong>:
        Red light indicates door a secured.</p>
    </div>

    ...

  </div>
  <script>
    ...
  </script>
</body>

Now you can see that the span tag become cleaner. Your page design should be free from cryptic code.

But hey, there is downside of this method! The script can only be placed at the bottom of the document.

Event Listener

In order to put the javascript on above document, we need to add an event listener that triggered when the page ready. The event is named as DOMContentLoaded.

We can rewrite the the function inside head tag, as below code:

<!DOCTYPE html>
<html>
<head>
...
<script>
  document.addEventListener("DOMContentLoaded", function(event) { 
    var alertButtons = document.getElementsByClassName("dismissable");
    
    for (var i=0; i < alertButtons.length; i++) {
      alertButtons[i].onclick = function() {
        this.parentElement.style.display='none';
        console.log('Close Button. Element ' + this.parentElement.id + ' dismissed');
        return false;
      };
    };
  });
</script>
</head>
<body>
  ...
</body>
</html>

In your text editor, this could be shown as below:

HTML Basic: Geany Editor: Internal

I also put a console.log to show the id of the span tag , so that you can debug easily using inspect element. Now the code should looks like something below:

    <div class="panel red display-container" id="red-danger">
      <span class="dismissable button large display-topright">&times;</span>
      <p><strong>Danger!</strong>:
        Red light indicates door a secured.</p>
    </div>

Or in a complete fashionen you can examine the code below:

<!DOCTYPE html>
<html>
<head>
   ...
</head>
<body>
  <div class="container">

    <h2>Relationship Alerts</h2>
    <p>To close the alerts, click on the X in the upper right corner:</p>

    <div class="panel red display-container" id="red-danger">
      <span class="dismissable button large display-topright">&times;</span>
      <p><strong>Danger!</strong>:
        Red light indicates door a secured.</p>
    </div>

    <div class="panel yellow display-container" id="yellow-warning">
      <span class="dismissable button large display-topright">&times;</span>
      <p><strong>Warning!</strong>:
        Yellow light indicates that something could go wrong.</p>
    </div>

    <div class="panel green display-container" id="green-success">
      <span class="dismissable button large display-topright">&times;</span>
      <p><strong>Success!</strong>:
        Green light indicates on schedule, on budget, all good.</p>
    </div>

    <div class="panel blue display-container" id="blue-info">
      <span class="dismissable button large display-topright">&times;</span>
      <p><strong>Info!</strong>:
        Blue light indicates that you are in electronics mode.</p>
    </div>

  </div>
</body>
</html>

Again, you can click the dismissable alert button. And see each button vanished one by one.

Javascript: Unobstrusive OnClick Event

External Javascript

As we did with stylesheet, we can put the javascript into external files. So that we can reuse the code in other page.

<head>
  <title>Example Assets</title>
  <script src="js/script.js"></script>
</head>

You can have the complete script here:

and the javascript here:

In your text editor, this could be shown as below:

HTML Basic: Geany Editor: External

One of my favorites javascript is livejs, so that whenever change happened in localhost, the page will be automatically refreshed. And I also like meta tags. Now we can complete our head tag as below:

<head>
  <title>Example Assets</title>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible"
        content="IE=edge,chrome=1">
  <meta name="viewport"
        content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <link rel="stylesheet" href="css/style.css">
  <script src="js/script.js"></script>
  <script src="js/live.js">
</head>

The result in browser is the same as previous example.


What’s Next?

Consider continue reading [ HTML - Developing Tips ].