I am currently grappling with a JavaScript mouse over event and encountering some difficulties

I am looking to dynamically change the background image of my body div whenever a link is hovered over. Here is a snippet of my code:

JAVASCRIPT:

var i = 0,
    anchors = document.querySelectorAll("zoom"),
    background = document.getElementById("body");

function backgroundChange() {
    "use strict";

    window.console.log("hey");

    if (event.target.id === "4Mo3We2Days") {
        background.style.background = "url('../Images/movies/4Mo3We2Days.png')";
    ...
    other specific ids
    ...
    }
}

function backgroundRemove() {
    "use strict";

    background.style.backgroundImage = "none";
}

for (i = 0; i < anchors.length; i += 1) {
    anchors[i].addEventListener("mouseover", backgroundChange, false);
    anchors[i].addEventListener("mouseout", backgroundRemove, false);
    window.console.log("yo");
}

HTML:

<!DOCTYPE html>
<html>
    <head>
        <link rel = "stylesheet" type = "text/css" href = "../CSS/JMWStyles.css">
        <title>Archives</title>
        <meta charset="UTF-8">
    </head>
    <body>

        <header>
            <img id = "logo" src = "../Images/logo.png" alt = "logo" href = "../JMW.htm"></img>
            <ul id = "navMenu">
                <li class = "nav"><a id = "button5" class = "navItem" href = "../JMW_Store.htm">Store</a></li>
                ...
                other nav items
                ...
            </ul>


        </header>

        <hr>

        <div>
            ** Please Note that these were written for the radio and were meant to be read aloud. There are many typos as
            well as odd things to read. If you would like, leave a comment so I can fix it! <br>
            &emsp; - Jake Winters
        </div>

        <hr>

        <div id = "body">
            <ul class = "centered">
                <li><a class = "zoom" id = "4Mo3We2Days" href = "MovieReviews/4Mo3We2Days.htm">4 Months 3 Weeks and 2 Days</a></li>
                ...
                other movie links
                ...
            </ul>
        </div>

        <footer>
            <hr id = "footerHr">

            <ul id = "socialMenu">
                <li class = "social"><a href = "spotify:user:1256028498"><img class = "footerImg" id = "spotify" src = "../Images/spotify.png" alt = "spotify"></a></img></li>
                ...
                other social media links
                ...
            </ul>
        </footer>

    </body>

    <script src = "../JS/JMW.js"></script>
    <script src = "../JS/archive.js"></script>
</html>

CSS:

#body {
    background-image: none;
    background-repeat: no-repeat;
    background-position: center;
}

I am uncertain if I am attaching the event listeners correctly. How can I determine the element that triggered the event within my defined functions? Is event.target.id the right approach?

I am trying to avoid using jQuery as I want to improve my understanding of basic JavaScript. However, if jQuery would be more suitable for this task, please explain why. Any guidance would be greatly appreciated. Thank you!

Additionally, I am considering styling the background images with a white rounded vignette and adjusting the alpha for consistency, but this is a secondary concern.

Answer №1

Your anchor selections were not made correctly. When targeting a class, make sure to include a dot before zoom:

anchors = document.querySelectorAll(".zoom"),

Additionally, remember to include the event argument for compatibility with browsers other than IE:

function modifyBackground(event) {

Answer №2

The main issue that needed to be corrected was your use of querySelectorAll("zoom"). It should have been querySelectorAll(".zoom") since you were targeting classes. This was causing a failure to access the desired links for event handling.

Additionally, there were some instances of invalid HTML code, such as not closing <img> elements.

It's best practice to utilize the event object that is automatically passed as the first argument to event handling functions. Accessing it directly as a global variable (event) is specific to old versions of Internet Explorer and may not work in all browsers. Using this to reference the DOM object that triggered the event is also recommended, for example this.id is equivalent to event.target.id.

Lastly, consider changing some of your variable names. For instance, using body as an id for anything other than the <body> element can lead to confusion.

I also included instructions to change the color of a section when the mouse hovers over it as a demonstration in the code below:

var i = 0,
anchors = document.querySelectorAll(".zoom"),
body = document.getElementById("main");

function backgroundChange(evt) {
  "use strict";
    // Event handling function
}

function backgroundRemove() {
    "use strict";
    // Function to remove background changes
}

for (i = 0; i < anchors.length; i += 1) {
    anchors[i].addEventListener("mouseover", backgroundChange);
    anchors[i].addEventListener("mouseout", backgroundRemove);
}
#main {
    background-image: none;
    background-repeat: no-repeat;
    background-position: center;
}
<header>
   <img id="logo" src = "../Images/logo.png" alt = "logo" href = "../JMW.htm">

   <!-- Menu links -->
   <ul id="navMenu">
     <li class="nav"><a id = "button5" class = "navItem" href = "../JMW_Store.htm">Store</a></li>
     <li class="nav"><a id = "button4" class = "navItem" href = "../JMW_Archives.htm">Archives</a></li>
     ...
   </ul>
</header>

<hr>

<div>
 ** Please Note that these were written for the radio and were meant to be read aloud. 
    There are many typos as well as odd things to read. If you would like, 
    leave a comment so I can fix it! <br>
    &emsp; - Jake Winters
</div>
...
</footer>

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

Arrange images in a fluid manner around other images

Check out the website I'm currently working on: metroweb.tk I'm in the process of designing a website that mimics the Windows 8 metro UI. However, I've encountered an issue with larger app icons such as notes and clocks sticking out. Is the ...

What is the best way to utilize eslint in Vue components?

I'm facing an issue with my .vue file that defines a component. Other .vue files are unable to see it properly due to linter errors. I keep getting ES Lint errors like: Cannot find module '../components/LinkButton'. I have tried several st ...

PHP: Bootstrap CSS for Carousels

I'm experiencing some difficulties with the Bootstrap CSS Carousel on my website. The left and right arrows seem to be unresponsive, and the slides are not transitioning automatically. I have been unable to identify the root cause of this issue. Belo ...

Silky animations in kinetic.js (html5 canvas)

I am seeking a better grasp on kinetic.js animation. Recently, I came across a tutorial at . After experimenting with the code provided, I managed to create an animation that positions my rectangle at x coordinate 100. However, I am struggling to achieve s ...

Are "Color Scheme" and "Color Palette" distinct from each other?

What is the difference between a color scheme and a color palette? In one of my projects, which is a web template, there are options for customers to customize. However, I find myself confused with the naming conventions for two color-related options. Op ...

What is the best way to set up jest to generate coverage reports for Selenium tests?

I recently made the switch to using jest for testing my JavaScript project after encountering coverage issues with mocha and chai. While my unit tests are providing coverage data, my Selenium tests are not. I've tried various solutions found in outdat ...

What is causing the duplication of leaves when using this DFS implementation?

I created an algorithm to compare if two trees have the same leaves. https://i.sstatic.net/lpO2C.png Both trees display matching leaf numbers in the exact order, resulting in a true outcome. Below is the code that I formulated: function leafSimilar(root ...

Having trouble with submitting a form through Ajax on Rails 4

Having models for advertisement and messages with forms that both utilize Ajax (remote => true) for submission. The message form submits perfectly, remains on the same page, and handles the response efficiently. However, the advertisement form fails to ...

Problem with transitions not working properly in Vue.js.The issue

Experiencing an issue with the Vue.js transition feature. Check out this link for reference. When the transition enters, it works smoothly, but when transitioning out, it's not functioning properly. File: genetic.vue <transition name="slide-f ...

Error in Javascript, exception was not handled

I have encountered an issue while using a javascript file named pull.js. This file is meant for implementing pulldown refresh functionality on iPad. However, when I use this file, it seems to interfere with other jQuery and javascript functionalities, caus ...

Placing a v-model within a Vue.js component

I am attempting to achieve something similar to this specific scenario, but I am struggling to find the appropriate technical terminology to describe it. Unfortunately, I haven't been able to locate a solution for this issue. <div id="app"> ...

Line up with miniature stature

How can I prevent the image in this row from getting a margin at the bottom when I resize the window? <div class="row-fluid"> <div class="span2"> <img src="https://s3.amazonaws.com/media.jetstrap.com/SLgRUEHSyGwQVfG4x6ed_curso_a ...

JavaScript JCrop feature that allows users to resize images without cropping

I'm currently attempting to utilize JCrop for image cropping, but I'm running into frustratingly incorrect results without understanding why. The process involves an image uploader where selecting an image triggers a JavaScript function that upda ...

Unexpected behavior is being encountered with the else statement, and there are compatibility issues with IE and Mozilla Browser in the overall script

Script is functioning as expected in Google Chrome, but is not responsive in IE and Mozilla browsers JavaScript code: <script src="jquery.min.js"></script> <script> function Run() { if(jQuery('#inputtext').val() == '0 ...

Modifying language in Kendo UI

I am currently using Kendo UI to develop grids and applying the data-filterable option for data filtration. My requirement is to switch the language from English to Polish. How can I achieve this? https://i.sstatic.net/J5PEa.png Below is the script I am ...

Exploring nested JSON through recursive iteration in JavaScript

Consider this JSON data containing comments that are fetched via AJAX call: json = 'comments': [ {'id':1,'parent':0}, {'id':2,'parent':1}, {'id':3,'parent':2}, {'id&apos ...

What could be causing the Bootstrap icon to remain the same size without changing?

Take a look at this piece of code: <div class = "banner-image w-100 vh-100 d-flex justify-content-center align-items- center"> <div class = "content text-center"> <i class="bi-chevron-compact-down bi-7x"&g ...

The challenge with using Telerik Rad Textboxes in conjunction with JavaScript

I am facing an issue where the server data is not displayed in a Rad Textbox until I click on it using JavaScript. The data is being populated correctly inside the textbox, but it remains invisible until clicked. function fillTextBox(name, sku, plu, nam ...

Responsive design is achieved through the use of CSS media queries targeting the

Could someone please clarify the meaning of the following value? Does it indicate that the output device must support exactly 256 colors, or is it acceptable for the output device to have 256 colors or fewer, or does the device need to support 256 colors ...

Determine whether the response from a jQuery AJAX call is in JSON format or binary. If it is found to be binary, proceed

I am currently using ajax to retrieve and download an xlsx file from a PHP script. The script has two possible types of responses: JSON format if there are any warnings preventing the download (such as incorrect parameters), or the xlsx binary stream if ev ...