JavaScript Events

Notes Home

Events in JavaScript are functions that react to interactions with the browser, such as user clicks, document loading and window scrolling. There are events for virtually everything you can think of.

 document.querySelector("#alert");
 var btn = document.querySelector("#alert");
 btn.onclick = function() {
  alert("Hello World!");
}

Events are part of the web api for interacting with web pages. Here's a list of events.

In JavaScript, we can use event handlers or event listeners to detect events and then execute some commands based on data extracted from the events.

onclick is a short hand function for a click event. The long version looks like this:

btn.addEventListener('click', function() { 
	alert('click'); 
});

So this is cool, but we need to be able to actually write JavaScript into our HTML pages, right? It's not that useful to write into the JavaScript console unless you're testing or debugging your already existing code.

Like CSS, we can add JavaScript to elements with an inline attribute, or to a document with an internal <script> element, or to multiple documents with an external <script> tag.

Inline:

<button onclick='alert("I am a button");'>Click me!</button>

Internal tag

<script type="text/javascript">
	var btn = document.querySelector('#confirm');
	btn.onclick = function() {
		var c = confirm("Does this make sense?");
		if (c) alert("Great!");
		else alert("Oh well...");
}
</script>

An external script tag looks similar, but has a src attribute, like an image, to a document that contains the javascript:

<script type="text/javascript" src="my-app.js"></script>

app.js has the JavaScript:

var btn = document.querySelector('#prompt');
var parent = btn.parentElement;
btn.onclick = function() {
	var response = prompt("Where are you from?");
	var r = document.createElement("p");
	r.innerHTML = response;
	parent.insertBefore(r, btn);
}

console.log

console.log() in JavaScript is like println in Processing. Like all languages, we need a way to print things to the console to see what works and doesn't it. It's extremely useful and easy to use, but you have to remember to be specific. You can put pretty much anything in the argument parentheses for console.log(), so make sure it's something useful, like an element, a variable, or something else that you want to be able to read. This is a good way to read data from various events.

document.body.onclick = function(ev) { console.log(ev); };