The mouse event listener fails to function in plain JavaScript

I've been tackling a fun little project from The Odin Project called "ETCH-A-SKETCH". The idea is to change the color of squares when the mouse hovers over them, but I'm having trouble getting the onmouseover event to trigger. Any idea what could be causing the issue?

index.html

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8" />
            <meta http-equiv="X-UA-Compatible" content="IE=edge" />
            <meta name="viewport" content="width=device-width, initial-scale=1.0" />
            <link rel="stylesheet" href="style.css" />
            <title>ETCH-A-SKETCH</title>
        </head>
        <body>
            <div class="container"></div>
    
            <script src="app.js"></script>
        </body>
    </html>

app.js

const body = document.querySelector('body');
const Btn = document.createElement('button');
const container = document.querySelector('.container');
const squares = document.querySelectorAll('.square');
body.append(Btn);
body.insertBefore(Btn, container);
Btn.innerText = 'Create A New Grid';

....

squares.forEach((square) => {
    square.addEventListener('onmouseover', (e) => {
        console.log(e);
        e.preventDefault();
        square.classList.add('zapper');
    });
});

style.css

.zapper {
    background-color: #fff;
}

.zapper:hover {
    background-color: black;
}

Answer №1

When utilizing event listeners, remember to use mouseover instead of onmouseover

For example:

square.addEventListener('mouseover', (e) => {

If you prefer to use onmouseover, it should be included in html attributes like this:

<button onmouseover="functionName()">

The on prefix is specifically for html attributes, so make sure to omit it when utilizing event listeners.

Answer №2

One issue arises from JavaScript's speed being exceptionally fast. The scenario often unfolds where your code completes execution before the DOM is fully rendered. Consequently, when attempting to add an event listener to your elements, these elements are not yet visible on the screen. It becomes imperative to instruct JavaScript to add the listener post DOM mounting.


window.addEventListener('DOMContentLoaded', (event) => {
    console.log('DOM fully loaded and parsed');

const body = document.querySelector('body');
const Btn = document.createElement('button');
const container = document.querySelector('.container');
const squares = document.querySelectorAll('.square');
body.append(Btn);
body.insertBefore(Btn, container);
Btn.innerText = 'Create A New Grid';

....

squares.forEach((square) => {
    square.addEventListener('onmouseover', (e) => {
        console.log(e);
        e.preventDefault();
        square.classList.add('zapper');
    });
});

});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Methods used on a server and methods used on a client-side application

In my ASP.NET application using C# 2.0, I have created objects for a database with properties that can be called natively or through a RESTful JSON API. These objects are used to convert data into HTML for display on the website. On the site, there are se ...

Error: react-testing-library throwing validateDOMNesting warning

Warning: validateDOMNesting(...): <tbody> cannot appear as a child of <div>. in tbody (created by TableBody) in TableBody (created by TableBody) in TableBody Inquiry: Is there a way to render the TableBody component within a table ...

Tips for resolving the issue of invalid functions as a child component in React

When I call a function that returns HTML code, everything works fine until I try to pass a parameter in. At that point, I receive an error saying "Functions are not valid as a React child." The issue is that I need to access the props from this function. T ...

Showing a database table in an HTML format using JavaScript

I am currently working on displaying a database table in HTML. I have written a PHP code snippet which retrieves the table data and formats it into an HTML table without any errors: function viewPlane() { if(!$this->DBLogin()) { $ ...

What is the best way to enclose a bootstrap row within a clickable link generated by the twitch.tv API?

Recently, I completed a JSON/JavaScript project for Free Code Camp that retrieves streamer information like their logo, current status, and display name. My goal is to enclose entire Bootstrap 3 rows in hyperlinks linked to the streamers' pages, elim ...

Maintaining Image Aspect Ratio within a Div with a Specified %width

Apologies for the repeated question, but my research hasn't yielded a solution I can apply. Inside a div with the specified styles, there is an image: <div class="thumb grid_6"> <img src="img/test2.jpg" alt="flavin" /> </div> . ...

React code to automatically scroll to the top of the page when the user clicks the

Whenever the URL changes or the page is reloaded in my project, I need it to scroll back to the top. While most scenarios work fine, I'm encountering an issue with the browser's back button. Despite a change in the pathname, the page fails to scr ...

Issues with getting full HTML content using selenium for web scraping

My task is to extract the discounted price of a product from a specific website. Upon inspecting the website, I found the following HTML structure: https://i.sstatic.net/LerWE.png This is what my code currently looks like: browser = webdriver.Chrome(exe ...

Creating a website without access to the internet

When I'm working on my laptop in locations without internet access, I need to build a website. How can I assess the progress of my pages without an active browser? ...

Implementing dynamic AngularJS functionality within an older HTML structure using JQuery

I am facing an issue while trying to load dynamic content using AngularJS. In my system, I have legacy pages that utilize JQuery for dynamic loading. However, as I am developing new features with AngularJS, I am encountering the same problem with dynamic ...

I am looking to enhance the readability of my asynchronous function calls

At the moment, I am handling my Promises by calling an async function and then chaining it with .then(). But I feel like there could be a more readable approach. This is how it currently works: const fetchData = async() => { const response = await ax ...

The jQuery code does not execute following the use of window.location.replace( url ) command

I'm facing an issue with my code that involves redirecting the page to the index page after clicking on a specific link ('#versionPageFromProdLink'). The index page contains certain content within a div, which I want to hide once the redirec ...

Are there any performance implications when using an excessive number of background images in CSS?

My website seems to be running too slowly based on user reports. I suspect that the background images in CSS may be causing the issue. The site uses a custom build system to concatenate and compress all CSS, create CSS sprites automatically, resulting in ...

Notification Click Event for PWA Service Worker

I am attempting to display a notification and trigger an action when it is clicked. try { navigator.serviceWorker.getRegistration() .then(reg => { reg.showNotification("Check out the video clip!", { body: "Cl ...

Is it possible to resize an image to fit within its parent div using only the parent div

Is there a way to ensure that an image inside a div resizes itself based on the dimensions of the div without distorting the ratio? <div class="w-50"> <img src="" class="w-full h-full image-cover"> </div> ...

Troubleshooting React Native's ScrollView issue with row direction and flexWrap not allowing scrolling

One issue I'm facing in my React Native app is with a ScrollView that contains a list of items wrapped in rows (flexDirection:'row', flexWrap:'wrap'). For some reason, the ScrollView is not scrolling properly... Here is the code f ...

Java REST service remains out of reach for JavaScript fetch call

Currently, I am in the process of learning about REST API. My goal is to make a call to a POST service implemented in Java from Javascript using fetch. However, I have encountered an issue where the request fails to reach the service whenever the @Produces ...

Uniting the client-side jQuery and server-side Express for enhanced functionality

Currently, I am deepening my understanding of Express/Node. My goal is to construct a basic HTML form that undergoes client-side validation (using jQuery/AJAX) while also being processed server-side (via Express.js). The application's complexity remai ...

Upon reloading, the dynamically generated table does not appear accurately

When a table is dynamically created using JavaScript/jQuery/html from an Ajax call, it initially displays correctly formatted. However, upon refresh/reload, the formatting of the table becomes incorrect. To address this issue, I have implemented a Promise ...

What is the best way to link to a CSS file located in a different directory while being in a subdirectory?

For a project I am working on, I am developing a simple streaming site and have organized my files into different folders. These folders include: HTML CSS Shows Within the "Shows" folder, there is a subfolder named "Testshow". I am facing an issue with ...