Using JavaScript Events in Common Web Development Scenarios

Juliet Ofoegbu
7 min readJul 19, 2023

In this article, we’ll learn how to use JavaScript events for some web development scenarios such as animations, form validations, navigation, image galleries, and infinite scrolling.

What are events?

Events in web development are used to handle users’ interaction with a website or web app. Events make webpages to be dynamic and interactive instead of static. When users perform actions on a webpage like clicking a button, typing characters into a field input, loading a webpage, pressing a keyboard key, or resizing a window, all these actions are called events.

There are different types of JS events such as keyboard events, mouse events, focus and blur events, form events, window events, and so on. We however won’t be looking at the types of events, but we’ll be focusing on how these events are used in common web development cases.

  • Animation: Animations bring life and interactivity to a webpage. Utilizing events gives developers the ability to trigger animations based on the user’s interaction with elements on a webpage like clicks, hover, and scroll. Here’s an example of how to use events for animations:
<style>
.animate {
width: 200px;
height: 200px;
background-color: red;
transition: width 0.5s, height 0.5s, background-color 0.5s;
}
</style>


<button id="animateBtn">Animate</button>
<div id="animatedElement"></div>


<script>
const animateBtn = document.getElementById('animateBtn');
const animatedElement = document.getElementById('animatedElement');

animateBtn.addEventListener('click', () => {
animatedElement.classList.add('animate');

setTimeout(() => {
animatedElement.classList.remove('animate');
}, 1000);
});
</script>

In the code above, we have 2 elements. One is a button with an id of animateBtn, and the other, is a div element with an id of animateElement. The JS code adds an event listener to the animateBtn element’s click event. And so, when the button is clicked, the “animate” class is added to the div.

This will then trigger the CSS animation that was defined in the styles. The animation is a box with a defined width, height, color, and transition properties for smooth animation. We also defined a setTimeOut function that removes the animate class from the div after 3 seconds.

  • Form validation: Events can be used to perform real-time form validations. This is useful in web development as it is used to ensure that characters inputted in a form follow a set of defined criteria before successful form submission. This can be used to validate users, prevent errors, guide users in form completion correctly, and provide instant feedback to users when they submit forms. In the code below, we’ll validate a password input field.
<style>
#passwordInput {
padding: 7px;
border-radius: 15px;
}
#passwordError {
color: red;
}
</style>

<input type="password" id="passwordInput" />
<p id="passwordError"></p>


<script>
const passwordInput = document.getElementById('passwordInput');
const passwordError = document.getElementById('passwordError');

passwordInput.addEventListener('input', () => {
const password = passwordInput.value;

if (password.length < 6) {
passwordError.textContent = 'Password should be at least 6 characters long.';
} else {
passwordError.textContent = '';
}
});
</script>

So, what the code above does is that it checks the password length and updates the passwordError element accordingly. This is possible because first, we attached an id to 2 elements. One, passwordInput, to the input field, and another passwordError to a <p> element. We then attached an event listener to the input element that checks the value typed in the input field to see the length. If the password length is less than 6, an error message appears prompting the user to type in more characters until the length is 6 or more, then the error message disappears.

Password validation

Form validation can also be used to check if all the input fields in a form are complete or have met certain criteria before they can be submitted. If not, you can choose to display an error message to users to enable them to complete the form accurately before submission. This feature is used in most if not all websites/web apps that require users to sign up or log in.

  • Navigation: When creating websites and we want users to be able to go to different sections of the website, we do so by navigation. JS events can be used to implement smooth scrolling, page transitions, and create dynamic navigation menus. We see examples of these navigations on most websites. It’s usually located at the very top of the website. Some however are located by the side. It doesn’t matter where it is located. The important thing is that it navigates users to different sections of the website.
  <nav>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>

<script>
const navLinks = document.querySelectorAll('nav a');

navLinks.forEach((link) => {
link.addEventListener('click', (event) => {
event.preventDefault();
const target = document.querySelector(link.getAttribute('href'));
target.scrollIntoView({ behavior: 'smooth' });
});
});
</script>

What the above JS code does is that it attaches a click event listener to each of the navigation links. Anytime any of the links are clicked, it prevents the default link behavior and smoothly scrolls down to the target element assuming you have a full website. The target element is specified in the href attribute in the <a> tag of each link.

  • Image Galleries: To create image galleries, you’d often need event interaction such as handling image clicks or swipes. It can be used to implement image carousel functionality, lightbox effect, and sliders that users can utilize to navigate through a large collection of images easily. For this example, we’ll be building an image gallery with lightbox functionality.
 <style>
#image {
padding: 7px;
border-radius: 15px;
}
</style>

<div id="imageGallery">
<img src="image1.jpg" id="image" alt="Image 1" />
<img src="image2.jpg" id="image" alt="Image 2" />
<img src="image3.jpg" id="image" alt="Image 3" />
</div>

<div id="lightbox" style="display: none;">
<img id="lightboxImage" src="" alt="" />
<button id="closeButton">Close</button>
</div>


<script>
const imageGallery = document.getElementById('imageGallery');
const images = imageGallery.querySelectorAll('img');
const lightbox = document.getElementById('lightbox');
const lightboxImage = document.getElementById('lightboxImage');
const closeButton = document.getElementById('closeButton');

images.forEach((image) => {
image.addEventListener('click', () => {
const src = image.getAttribute('src');
const alt = image.getAttribute('alt');

lightboxImage.setAttribute('src', src);
lightboxImage.setAttribute('alt', alt);
lightbox.style.display = 'block';
});
});

closeButton.addEventListener('click', () => {
lightbox.style.display = 'none';
});

</script>

I remember my first time building an image gallery when I started learning JavaScript. I was so excited cos I got to play around with this. Below is an image of what I built to demonstrate the Image Galleries event example.

NB: There’s a JavaScript library called Lightbox that is used to display images or videos by filling out the rest of the screen and dimming out the rest of the webpage. It is like an overlay.

  • Infinite Scrolling: Have you ever visited a webpage and noticed that contents are dynamically loaded as you scroll? That functionality is called infinite scrolling. The scroll event in JS can be used to achieve this. The web browser listens for the scroll event to fetch and append new content as users scroll down the webpage. This creates a good experience for users.
<style>
.heading {
position: sticky;
top: 0;
text-align: center;
background-color: white;
line-height: 2.5rem;
right: 0;
}

.container {
display: flex;
flex-wrap: wrap;
}

.text {
margin: 5px;
background-color: lightblue;
border: black 0.2rem solid;
text-align: center;
font-size: 10rem;
width: 100vw;
height: 200px;
}
</style>

<h2 class="heading">Infinite scrolling</h2>
<div class="container"></div>

<script>
const container = document.querySelector(".container");

let totalCards = 0;
function loadCards(numCards = 10) {
for (let i = 0; i < numCards; i++) {
totalCards++;
const card= document.createElement("div");
card.classList.add("text");
card.appendChild(document.createTextNode(totalCards));
container.appendChild(card);
}
}

loadCards();
window.addEventListener("scroll", () => {
if (
window.scrollY + window.innerHeight >=
document.documentElement.scrollHeight
) {
loadCards();
}
});
</script>

What we’ve been able to achieve with the above lines of code is to demonstrate an implementation of infinite scrolling where more boxes are dynamically loaded as users scroll down to the bottom of the page. How did we do this?

  1. We set a div to include a “container” class in the HTML code.
  2. We then define a variable called “container”. This selects the assigned reference to the container element using document.querySelector().
  3. The totalCards variable is initialized to keep track of the total number of boxes.
  4. The textCards function is defined to generate and append the desired number of boxes to the container. Each box is represented by a <div> element with the class "text" and contains a text node with the post number.
  5. Initially, loadCards is called without any arguments to load 10 boxes. You can change the value to any number you want to load initially.
  6. An event listener is added to the scroll event on the window object using the window.addEventListener()function.
  7. The main functionality is this. When the user scrolls, the event listener checks if the user has reached the bottom of the page by comparing the sum of window.scrollY (current scroll position) and window.innerHeight (visible height) with document.documentElement.scrollHeight (total height of the document).
  8. If the user has scrolled to the bottom, loadCards() is called again to load more boxes to the page.
Infinite scrolling

And with that, we have come to the end of the article.

Conclusion

Events play a very crucial role in modern web development as they enable developers to create interactive, dynamic, and functional web applications. In this article, we explored the practical applications of events in various common web development scenarios, including animations, form validations, navigation, image galleries, and infinite scrolling. It is important that as developers we know how to use these events effectively to enhance user experience and improve functionality in our websites and web apps.

I hope you were able to understand everything taught in this article. If you do have any questions or need clarifications on any aspect of the article, feel free to drop it in the comment section and I’ll get back to you. Happy coding!

--

--