• About
  • Write For Us
  • Contact
  • Top 50 Photography Blogs
  • Resources
  • Forum

IndustryDev

  • Design
    • Photoshop
    • Lightroom
    • Camera Raw
    • Bridge
  • Development
    • HTML
    • CSS
    • Javascript
    • PHP
    • Dev Tools
    • WordPress
  • Photography
  • Blogging
  • Technology
  • Inspiration
You are here: Home / Javascript / JavaScript Events & Event Listeners

JavaScript Events & Event Listeners

May 2, 2015

JavaScript Events & Event Listeners

In this post, I’m going to talk about events in JavaScript. Events are those things that happen on, in and around a web page. They are all over and occur even when you think they aren’t. In short, I’ll be talking about what JavaScript can do when someone clicks something, when a page is loaded, when a mouse is moved, when someone fills in a field, when a key on a keyboard is pressed…you get the idea. And since events happen all the time, JavaScript can be utilized quite powerfully, in ways that can truly make your pages come alive.

onclick Event

The onclick property returns the click event handler code on the current element.

Let’s start writing some code. In this first example, I’m going to give you the most basic of basic scenarios you might find. It doesn’t get any easier than this:

<script>
document.onclick = function() {
    alert("You clicked anywhere!");   
}
</script>

In this example, I’m using the script tags. This is so I don’t have to set up a real document and link my JavaScript file to it. If this were an actual website, I would do things correctly, but since we’re here to learn, just pretend those script tags aren’t there. If you’d like to try this script out for yourself though, please feel free to copy/paste the above and use it.

Anyway, what we’ve got in the above code is the use of an onclick event. The onclick event occurs when your specified element is clicked by a user. In the case above, I chose to have the entire document as the click target, so if you were to click anywhere on the page, an alert box would pop up with text that says, “You clicked anywhere!” Also, you can see that I’ve got the target (document) tied to the event (onclick) tied to a function (function()). When the event occurs on the target, the function executes. In this case, the function is an alert box.

Let’s try another example and this time, let’s build the page out a bit.

<!DOCTYPE html>
<html>
<body>
    
<p id="myText">This is my text. Click it if you dare.</p>
    
<script>    
var clickedText = document.getElementById("myText");
clickedText.onclick = function() {
    alert("You clicked the text.");   
}    
</script>

</body>
</html>

As you can see, I added some HTML elements, just to make things seem as lifelike as possible.


In this example, I included a paragraph that has an ID associated with it. The ID is called, myText. This is going to help me refine my click target, as opposed to having the entire page a clickable element.

After the paragraph and inside the script tags, I used the getElementById() method to get the ID called myText. After that, I associated myText with a variable that I named clickedText. Now that I have a simple variable, it’s easy to create an event response.

As you can see, after the newly defined variable statement, I created a function that would execute during an onclick event and associated that with my clickedText variable. Now, if someone clicks on the target text, they receive an alert box that says, “You clicked the text.”

Let’s do one more example and this time, let’s throw in some areas we learned about in one of my previous posts. This should be a fun one.

<!DOCTYPE html>
<html>
<body>

<p>Want to try something? Click the button (if you dare).</p>

<button onclick="myFunction()">Click Me</button>

<p id="myText"></p>

<script>
function myFunction() {
    document.getElementById("myText").innerHTML = "You daring fool!";
}
</script>

</body>
</html>


Okay, let’s see if I can go through this one clearly.

First, I created a paragraph with an instruction in it. I dared the page visitor to click the button. Inside the button they are supposed to click on, I added the onclick event to coincide with a function that I’ve written towards the bottom of the page.

After the button, I created an empty paragraph element that uses the ID called myText. This paragraph will be populated with the text that’s created when the function directly below it is called by the button click. Still with me?

Let’s talk about the function. Again, we have an anonymous function that holds a statement. This time, we took advantage of what we learned in my previous post and used the getElementById() method to get the ID myText from the empty paragraph above. Once we get that ID, we have the ability to use the innerHTML property to fill the paragraph with some text. In this case, the text is “You daring fool!”

So, to make a short story even shorter, a page visitor is instructed to click a button. Once they click it, a chain reaction is set. The button enacts the myFunction() function, which gets the the myText ID, which gives the ability to populate the above paragraph with text. Cool? If you’d like, you can copy/paste the code to see it work.

onload Event

An event handler for the load event of a window.

Let’s talk about the “window” for a moment. Here, I grabbed this from the MDN site:

“The window object represents a window containing a DOM document; the document property points to the DOM document loaded in that window.”

So, the window encapsulates the document.

There’s an issue when attaching your JavaScript file to your web page in the wrong spot in your code. If you, for example, call your JavaScript file up in your head element and that file is supposed to run something that hasn’t yet been loaded on your HTML page, nothing will happen. If you load your JavaScript file down at the bottom of your page, right before the closing body tag, then your code will run properly. Due to this issue, some developers choose to use the onload event.

But that’s not what I wanted to talk about today. If you’re interested in the scenario that I just described, you can do some research on it for the best way to handle it.

Let’s go over a quick example of what some JavaScript onload code might look like:

<!DOCTYPE html>
<html>
<body onload="sayHello()">

<script>
function sayHello() {
    alert("Hello There!");
}
</script>

</body>
</html>

The code above is very simple. As you can see, I’ve called the sayHello() function from the opening body tag. So when the page loads, the function will run. In this case, the function opens an alert box that says, “Hello There!”

Here’s another code example:


<!DOCTYPE html>
<html>
<body onload="sayHello()">
    
<p id="hello"></p>

<script>
function sayHello() {
    document.getElementById("hello").innerHTML = "Welcome to my web page.";
}
</script>

</body>
</html>

In the above code, I gave pretty much the same example as one of the previous examples in this post, but instead of using the onclick event, I used the onload event. So no user interaction would have to take place beyond visiting the web page in question. In this case, when the user visits this web page and it loads, the following text would be inserted into the paragraph element:

Welcome to my web page.

onfocus & onblur Events

The onfocus and onblur events often work together and often can be found hanging around web forms. In the most simple sense, the onfocus event triggers an event when an element is focused upon, such as a form field being clicked on. The onblur event is the opposite – an event is triggered when an element’s focus is removed, such as a form field being clicked away from. Let’s see these two in action.

<!DOCTYPE html>
<html>
<body>

Type something in the box: <input type="text" id="inputText" onfocus="clickIn()" onblur="clickOut()">

<script>
function clickIn() {
    document.getElementById("inputText").style.background = "blue";
}

function clickOut() {
    document.getElementById("inputText").style.background = "orange";
}
</script>

</body>
</html>

For this first example, I created a form field that asks the user to type something. When the field is clicked in, the background of the field turns blue. When the field is clicked away from, it turns orange.

If you look at the code above, you’ll see that I utilized the onfocus and onblur events right inside the input element. This is one way to do it, but you can also do it another way, which I’ll show you next. Anyway, within the input element, I associated both events with their respective functions called clickIn() and clickOut().

Inside the script element, I wrote two functions. The first one gets the ID from the input element and changes the style (color) of it when it’s clicked on. The second function does the same thing, but changes the color when the element is clicked away from.

Let’s take a look at another code example:

<!DOCTYPE html>
<html>
<body>

Type something in the box: <input type="text" id="inputText" value="Write something here.">

<script>    
var inputField = document.getElementById("inputText");
    
inputField.onfocus = function() {
    if ( inputField.value == "Write something here." ) {
        inputField.value = "";   
    }
}

inputField.onblur = function() {
    if ( inputField.value == "" ) {
        inputField.value = "Write something here.";   
    }
}  
</script>

</body>
</html>


In the above code, I (again) created an input field. This time, I didn’t include any events inside this element. I simply named it with an ID of inputText. I also gave the field an initial value of “Write something here.”

If you look further down into the script element, you’ll see that I used the getElementById() method to get the inputText ID and then I stored it in a variable called, inputField. Then, I wrote two functions using that variable. The first function uses the onfocus event and the second uses the onblur event. Both functions include an if statement that asks whether or not something exists.

In the first function, the if statement asks if the value “Write something here.” exists when the input field is clicked on. If it does, change the value to nothing. In the second function, the if statement asks if the field is empty when the field is clicked away from. If it is, insert the field with the value, “Write something here.” Pretty cool.

Timing Events

In JavaScript, when you’d like to execute some code at specified time-intervals, you set it. When you want to stop the time-intevals, you clear it. When it comes to setting, there are generally two timing events you want to concern yourself with. They are setInterval() and setTimeout(). When it comes to clearing, again, there are generally two timing events you want to concern yourself with. They are clearInterval() and clearTimeout().

Take a look at these quick definitions:

setInterval() – The setInterval() function initiates a function, again and again, specifically at the times you set.

setTimeout() – The setTimeout() function initiates a function after waiting the amount of time you set.

clearInterval() – The clearInterval() function stops the function that was initially executed by the setInterval() function.

clearTimeout() – The clearTimeout() function stops the function from executing that was initiated by the setTimeout() function.

In order to make the above ideas more clear, I’m going to give some code examples. As usual, I’ll go over them below.


The first example I’m going to give is really simple. It’s just to show you how the setTimeout() function can possibly work. Take a look:

<!DOCTYPE html>
<html>
<body>

<p id="pageText"></p>

<script>
function putText() {
    document.getElementById("pageText").innerHTML = "This text took 5 seconds to appear.";
}
    
setTimeout(putText,5000);
</script>

</body>
</html>

Like previous examples, I placed an empty paragraph element in the page and used an ID, but this time called it pageText. After that, I wrote a function and used the getElementById() method to get the paragraph ID. After that, I used the innerHTML property to set the text inside the paragraph to “This text took 5 seconds to appear.” The only thing I had left to do was to somehow make the text appear. In this case, I chose to use the setTimeout() function to hold back the appearance of the text by five seconds.

In this next example, we’re going to clear the timeout.

<!DOCTYPE html>
<html>
<body>

<p id="pageText"></p>

<script>
function putText() {
    document.getElementById("pageText").innerHTML = "This text took 5 seconds to appear.";
}
    
timer = setTimeout(putText,5000);
</script>
    
<button onclick="clearTimeout(timer)">Stop the Text From Appearing</button>

</body>
</html>

This is the same code as above, but with a few modifications. First, in order for the clearTimeout() function to work, I needed to set the setTimeout() function to a variable. I did that and called the variable “timer.” Next, I used a button for the clearTimeout() function. When the button is clicked, the clears the timeout variable and halts the text from appearing on the page. The only thing is, the button needs to be clicked some time within the five seconds before the text appears.

Now, let’s take a look at the setInterval() function. Check out the code below:

<!DOCTYPE html>
<html>
<body>
    
<script>    
function alertBox() {
    alert("Hello There");
}
    
setInterval(alertBox,3000);    
</script>

</body>
</html>

In the above code, I wrote a function called alertBox that pops up an alert box every three seconds. The first alert box takes three seconds to appear and once you close the box, the box waits another three seconds before it appears again. This will go on forever, unless you stop it. To do that, take a look below:

<!DOCTYPE html>
<html>
<body>
    
<button onclick="clearInterval(popUp)">Stop The Damn Box</button>
    
<script>    
function alertBox() {
    alert("Hello There");
}
    
var popUp = setInterval(alertBox,3000);
</script>

</body>
</html>


Looks familiar, doesn’t it? Just like last time with the setTimeout() function, in order to stop the setInterval() function from continuing on forever, we had to set it to a variable. This time, I named the variable “popUp.” By doing this, we had a variable to clear. In order to take advantage of that, I created a button outside the script with the clearInterval() function inside of it. When a user clicks the button, the alert box stops appearing. It’s that simple.

Well, we’re at the end of another post. If you’d like to learn more about JavaScript, please check out my JavaScript category. I write almost every day, so enjoy and let me know what you think!

Related posts:

  1. What is the DOM?
  2. Creating & Including WordPress Header & Footer Files
  3. Learning CSS Selector Basics
  4. Structure of an HTML Web Page
  5. What is JavaScript?

Filed Under: Javascript

What’s Next? Email Updates!

If you enjoyed reading this post, why not consider signing up to receive others like it by email? It's so easy and you can unsubscribe at any time.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Connect With Me

  • Facebook
  • Instagram
  • Pinterest
  • RSS
  • Twitter

Copyright © 2021 · IndustryDev.com Web Design & Photography Blog · About · Write For Us · Contact · Privacy / Terms · Sitemap