Can I use the mouseover event on an image to display a sibling div?

Hi everyone! I'm fairly new to web development and I could really use some advice. I'm trying to implement a mouseenter event on an img tag to show a sibling div, but I'm encountering some strange behavior. The mouseenter event seems to be working fine for every img tag except for the ones in the first row of the grid. In the desktop view, both trackid-img and stussy-img are not working, and in mobile view, only trackid-img is not working. Am I approaching this incorrectly? Would it be better to place these images inside a div as a background image instead of using img tags, and then apply the mouseenter/hover effect to the div? Essentially, I just want to hover over the image and have another element revealed, which would be links related to the hovered image.

var trackid = document.querySelector(".trackid-img")
var stussy = document.querySelector(".stussy-img")
var caltrends = document.querySelector(".caltrends-img")
var br8s = document.querySelector(".br8s-img")

var trackid_links = document.querySelector(".trackid-links")
var stussy_links = document.querySelector(".stussy-links")
var caltrends_links = document.querySelector(".caltrends-links")
var br8s_links = document.querySelector(".br8s-links")

trackid.addEventListener('mouseenter', showTrackidLink)
stussy.addEventListener('mouseenter', showStussyLink)
caltrends.addEventListener('mouseenter', showCaltrendsLink)
br8s.addEventListener('mouseenter', showbr8sLink)

function showTrackidLink(){
    trackid_links.style.visibility = "visible"
}

function showStussyLink(){
    stussy_links.style.visibility = "visible"
}

function showCaltrendsLink(){
    caltrends_links.style.visibility = "visible"
}

function showbr8sLink(){
    br8s_links.style.visibility = "visible"
}
.projects {
    height: 100vh;
    background: linear-gradient(to right, rgb(26, 26, 26), rgb(2, 2, 2));
}

.project-container {
    position: relative;
    top: 10vh;
}

.work-row {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
}

.work-col {
    margin: 1rem 0;
    margin-left: auto;
    margin-right: auto;
}

.project-card {
    position: relative;
    min-height: 38vh;
    width: 36rem;
    text-align: center;
}

.trackid-img {
    position: relative;
    top: 10vh;
    height: auto;
    width: 30rem;
}

.stussy-img {
    position: relative;
    top: 2vh;
    height: auto;
    width: 15rem;
}

.caltrends-img {
    position: relative;
    top: 4vh;
    height: auto;
    width: 16rem;
}

.br8s-img {
    position: relative;
    top: 10vh;
    height: auto;
    width: 20rem;
}

.work-link {
    visibility: hidden;
}

.trackid-links {
    position: relative;
    top: 20vh;
}

.stussy-links {
    position: relative;
    top: 2vh;
}

.caltrends-links {
    position: relative;
    top: 10vh;
}

.br8s-links {
    position: relative;
    top: 15vh;
}
    <section class="projects">
        <div class="outer-container">
            <div class="project-container">
                <div class="work-row">
                    <div class="work-col">
                        <div class="project-card trackid-card">
                            <img class="trackid-img" src="images/TRACKID.png">
                            <div class="work-link trackid-links">
                                <a href="">
                                    <img class="github-img" src="images/github.png">
                                </a>
                                <img class="linkedin-img" src="images/linkedin.png">
                            </div>>
                        </div>
                    </div>
                    <div class="work-col">
                        <div class="project-card stussy-card">
                            <img class="stussy-img" src="images/stussy.png">
                            <div class="work-link stussy-links">
                                <a href="https://github.com/br8S/Stussy-Landing-Page">
                                    <img class="github-img" src="images/github.png">
                                </a>
                                <a href="https://br8s.github.io/Stussy-Landing-Page/">
                                    <img class="linkedin-img" src="images/linkedin.png">
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="work-row">
                    <div class="work-col">
                        <div class="project-card caltrends-card">
                            <img class="caltrends-img" src="images/CALTRENDS.png">
                            <div class="work-link caltrends-links">
                                <img class="github-img" src="images/github.png">
                                <img class="linkedin-img" src="images/linkedin.png">
                            </div>
                        </div>
                    </div>
                    <div class="work-col">
                        <div class="project-card br8s-card">
                            <img class="br8s-img" src="images/br8SLOGO.png">
                            <div class="work-link br8s-links">
                                <img class="github-img" src="images/github.png">
                                <img class="linkedin-img" src="images/linkedin.png">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>

Answer №1

When you have the desire to execute the same action regardless of the image being hovered over, it is best practice to avoid creating separate event handlers and instead utilize a single one. The key to achieving this is to use relative references to the next sibling element following the one that triggered the event, rather than depending on unique identifiers such as ids or class names.

Furthermore, insteading of establishing individual event handlers for each image, you can set up a single handler at a common ancestor of all images and allow the event to propagate up to that ancestor. Subsequently handling the event there and making decisions based on the actual triggering element makes use of a concept known as "event delegation", which significantly enhances the code's efficiency, performance, and scalability.

In the provided code below, you will observe an additional class named mouse assigned to any image responsible for initiating the event. Despite the absence of loops, references to IDs or distinct classes, and repetition of similar functions, the functionality remains intact. Adding a new project-card in the future only necessitates inserting the appropriate HTML structure alongside the existing content for seamless integration without further modifications required.

// Establish a single event handler on a shared ancestor
// of all potentially mouseovered images
document.querySelector(".project-container").addEventListener("mouseover", function(event){
  // Identify if the event originated from one of the
  // images designed for triggering this event (each image with 
  // this functionality has been given an extra class 'mouse' in the HTML)
  if(event.target.classList.contains("mouse")){
    // Make the next sibling element visible
    event.target.nextElementSibling.classList.remove("work-link");
  }
});
.projects {
    height: 100vh;
    background: linear-gradient(to right, rgb(26, 26, 26), rgb(2, 2, 2));
}

/* Remaining CSS styles omitted for brevity */
<section class="projects">
        <!-- HTML markup for projects section -->
</section>

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

Can a Django form be configured to hide submitted values using display:none?

As I was working on submitting a form in Django with multiple details, I came up with the idea to split it into sections. The first set of details would be hidden initially, and upon clicking the next button, the next set of details would be displayed fo ...

Is it possible to assign functions to each keystroke that does not correspond to a specific keybinding in Angular?

In Angular, there are events tied to keybindings or actions like (focus), (blur), (keydown), and more. You can bind specific keybinds to certain keys as well, such as (keydown.enter), (keydown.alt), etc. Is there a method to trigger an event only when it ...

Exploring methods to detect when a PHP page has been printed using the 'ctrl+p' shortcut and then subsequently updating

Hey there! I'm currently managing a php website that functions as an accounting system. Within this system, there are receipts, invoices, and other forms of documentation in use. However, I've encountered a problem with the main table in my myS ...

Numerous Radio Buttons

I am currently working on creating a quiz similar to those found on Buzzfeed and Zimbio. I apologize if this question has been asked before, but despite my efforts in searching, I have not been able to find the answer I am looking for. In this quiz, partic ...

Closures are like the "use" keyword in PHP or the capture list in C++, but they play a similar role in JavaScript and other transpiler languages

PHP has a useful feature with the use keyword, which allows for the usage of 'external' variables in closures. For example: $tax = 10; $totalPrice = function ($quantity, $price) use ($tax){ //mandatory 'use' return ($price * $quan ...

Tips for choosing the desired test to execute with Nightwatch Programmatic API

Currently, I am in the process of developing a web application that enables me to execute Nightwatch tests through a visual interface. At this point, I have successfully been able to run all my tests using a post request from my web app utilizing the Nig ...

The error message "Encountered an issue when trying to access properties of undefined (reading 'getState')" was

Currently working on developing an app that utilizes a Django backend and React frontend. The goal is to enable users to log in, receive refresh and access tokens from Django, store the token in local storage, and redirect authenticated users to a static p ...

Archive a webpage with refreshed content using ajax

Is there a way to save a webpage that has been updated through an ajax request? I'm looking to preserve basecamp message threads, but exporting is not possible since I am not the account owner. When attempting to use the javascript command below: jav ...

Tips for incorporating Bootstrap classes into a React project, setting the className attribute to an empty string

After setting up Bootstrap and Create-React-App using npm on my local machine, I proceeded to create a new React app. The first component I worked on was counter.jsx: import React, { Component } from 'react'; class Counter extends Component { ...

Issues arise with the behavior of Bootstrap design when adapting to different screen sizes, as well as

I am currently working on designing my personal portfolio using Bootstrap. I have made some progress with the setup, but I am encountering some issues. When I resize the window, the top menu collapses into a button. However, when I click on the button, n ...

Error in Node.js child_process: unable to access the property '_writableState' as it is undefined

I'm currently working on integrating ffmpeg's functionality into a Node.js API by utilizing the child_process library. However, I encounter an error when trying to pass data to ffmpeg's stdin pipe, specifically getting a TypeError: Cannot re ...

Is it possible in PHP to iterate through a query and sort it into a designated column according to a specific value?

I'm working with Laravel and trying to display data from a query in an HTML table. The table contains columns such as id, user, and shift. There are around 100 entries, with the shift column containing values like A, B, C, or D. My goal is to organize ...

Arranging adjacent div blocks to maintain alignment in a stylish way

I am facing an issue with divs that are placed side by side inside a table. These divs have been styled to appear as colored blocks. Everything seems fine when the text within each div fits on two lines, however, if it overflows onto another line, the en ...

What criteria do web browsers use to determine the order in which to apply @media queries when there are multiple relevant queries for the device

My website requires adjusting element positioning based on specific resolutions. One example is this media query: @media all and (max-width: 385px) And another one: @media all and (max-width: 500px) The device I am using has a width below 385px, but i ...

Unable to display JSON results in a tabular format

After successfully implementing the AJAX method in jQuery, I am able to receive a response. However, I am encountering difficulties when trying to display the arrays in a table format. success:function(resp){ var json =JSON.parse(JSON.stringif ...

Utilizing a JavaScript variable within a jQuery function as an attribute

var image = "path.png"; Is it possible to include the 'image' variable in the jQuery function like this? $('#mapfoto').prepend('<img id="theImg" src="http://path.gr/" + image />'); ...

Is there a way to access hover effect information in Atom editor similar to how it appears in VScode?

Is there a specific plugin required in Atom to display information when hovering over variables, objects, or functions similar to intellisense? VSCode does this automatically, but I am looking for the same functionality in Atom. https://i.stack.imgur.com/ ...

What is causing my ReactJS web application to not recognize the cookies being sent by the backend server?

I have a web application with a frontend built in ReactJS and a backend built in HapiJS. The backend is running on http://localhost:3000 and the frontend on http://localhost:1234. My goal is to implement authentication using cookies. I am using Axios in m ...

filtering elements with selectable functionality in jQuery UI

I'm trying to exclude the <div> children from being selected within this list item and only select the entire <li>. The structure of the HTML is as follows: <ul id="selectable"> <li> <div id="1"></div> ...

Adding an icon to the Autocomplete TextField in MUI v5 in Reactjs: A step-by-step guide

I created an autocomplete feature with the code below and attempted to display an icon after selecting each item, but unfortunately, it didn't work as expected! import { useState } from 'react' import { TextField,InputAdornment ,Autocomplete ...