Oct 20, 2022
We also use JavaScript on the client-side for code
that runs in the browser (as opposed to server-side
which runs on Node.js). These JavaScript files go into
the /public/javascripts
directory of our
project. That means that a file called script.js would
be sourced in a handlebars template like this:
<script src="/javascripts/script.js"></script>
It is very important to recognize the difference between our server-side and client-side code. Treat them as separate environments. For example the client-side code does not get access to the variables used in the server-side code or the ability to use modules.
There are a few different ways that we can call JavaScript on our client-side pages, but one of those ways is via event handlers, which will trigger when certain events occur. For instance, the most common event we will use in this course is onclick.
<button type="button" onclick="doSomething()">
Click Me!</button>
This means that when the button is clicked, it will call the doSomething() function. It can be useful to have one function that powers lots of buttons, but you typically still need to know which button was clicked.
You can pass in the element that was clicked using the “this” keyword:
<button type="button" onclick="doSomething(this)">
Click Me!</button>
It is often then useful to use traversal to do something that is in proximity of the button clicked. For example:
function doSomething(element) {
element.parentNode.remove(); //remove the button's parent
}
<!DOCTYPE html>
<html> <body>
<h2>JavaScript Timing Sample</h2>
<p>Click on "Try it". Wait 5 seconds, and the page will alert "Hello How are you!!".</p>
<button onclick="setTimeout(myFunction, 5000);">Try it</button>
<script>
function myFunction() {
alert('Hello How are you!!');
}
</script>
</body>
</html>
<h2>JavaScript HTML Events</h2>
<p>Click the button to display the date.</p>
<button onclick="displayDate()">The time is?</button>
<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
<p id="demo"></p>