Filtering out the item that is being hovered over from an array

I am trying to dynamically apply an .inactive class to all elements in an array, except the one that is currently being hovered over. I want to accomplish this using the filter function, but I am unsure how to exclude the .item element that is triggering the mouseover event. At the moment, all items are receiving the .inactive class.

const items = document.querySelectorAll('.item');

[...items].forEach(link => {
    link.addEventListener('mouseover', function() {
        console.log(link)
        const inactives = [...items].filter(item => link)
        inactives.forEach(inactive => {
            inactive.classList.add('inactive')
        });
    });
    link.addEventListener('mouseout', function() {
        [...items].forEach(item => {
            item.classList.remove('inactive')
        });
    });
});
.item.inactive {
  opacity: 0.5;
}
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
<div class="item">Item 4</div>
<div class="item">Item 5</div>
<div class="item">Item 6</div>
<div class="item">Item 7</div>

Answer №1

If you want to adjust your filter, consider comparing it to the current link:

const inactives = [...items].filter(item => item !== link)

It might be a good idea to assign the inactive class to all links initially.

To simplify the process, you can add the inactive class to all items when the mouse is not over them, and remove it from the hovered item. This eliminates the need for filtering the links.

const items = document.querySelectorAll('.item');

[...items].forEach(link => {
    link.classList.add('inactive');

    link.addEventListener('mouseover', function() {
        link.classList.remove('inactive');
    });

    link.addEventListener('mouseout', function() {
        [...items].forEach(item => {
            item.classList.add('inactive');
        });
    });
});
.item.inactive {
  opacity: 0.5;
}
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
<div class="item">Item 4</div>
<div class="item">Item 5</div>
<div class="item">Item 6</div>
<div class="item">Item 7</div>

Answer №2

Most of your code is correct, just a few adjustments are needed to make it function properly.

Take a look at the comment provided below.

Let's consider an example for better understanding.

const items = document.querySelectorAll('.item');
[...items].forEach(link => {
    link.addEventListener('mouseover', function() {
        const inactives = [...items].filter((item) =>  item != link) // retrieves all items except the current one
        
        link.classList.remove('inactive') // removes 'inactive' class from the current item
        inactives.forEach(inactive => {
            inactive.classList.add('inactive')
        });
    });
    
    link.addEventListener('mouseout', function() {
        [items].forEach(item => {
         if (item.classList)
            item.classList.remove('inactive')
        });
    });
});
.item.inactive {
  opacity: 0.5;
}
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
<div class="item">Item 4</div>
<div class="item">Item 5</div>
<div class="item">Item 6</div>
<div class="item">Item 7</div>

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

Is the eval() function initially used to directly translate the evaluated string?

Try running this code snippet in your browser: eval("(function() { console.log(JSON.parse('" + JSON.stringify('THIS IS COOL') + "')); })()"); It will output THIS IS COOL, however, if you run the following: eval("(function() { console ...

The result from Axios yields an [object Promise]

Utilizing the Flickr API, I am receiving feed images from their platform. In my Vue application, I have a computed property called filteredImages: computed: { filteredImages: async function() { return axios.get('https://api.flickr.com/services/feed ...

Issue with Typescript Application not navigating into the node_modules directory

After attempting to load the app from the root directory of our server, it became clear that this was not a practical solution due to the way our application uses pretty URLs. For instance, trying to access a page with a URL like http://www.website.com/mod ...

Place a user input field within a div element having the specified class

I am trying to insert an HTML input element into the following div: <div class="sss" style="padding-top:2px"> <center> <input value="test1" name="name1" type="submit" > <input value="test2" name="name2" type="submit"> </c ...

Can sets outrun arrays in terms of speed?

I am currently working on finding the intersection of 2 arrays using sets. Despite knowing that sets should provide a faster runtime, I was surprised to see that my code's performance is not improved with the use of sets. Specifically, in my notebook, ...

Error in Laravel: The source map for js/app.js could not be located, request failed with a status code 404

I recently started using laravel and keep encountering the following error message in the browser console: Source-Map-Error: request failed with status 404 Resource-Address: Source-Map-Address: popper.js.map I'm struggling to pinpoint the ...

How can one HTML form be used to request a unique identifier from the user, retrieve a record from the database, parse it into JSON format, and then populate an HTML page form using the

As someone who isn't an expert in any specific coding language, I have a knack for piecing things together to make them work. However, my current challenge is stretching my technical abilities a bit too far. Here's what I'm trying to achieve ...

Updating a JavaScript global variable within a click event function: A quick guide

I am currently using Javascript and jQuery to retrieve the mouse coordinates of a click event for use in other Javascript functions. The issue I am facing is that global variables set within an event function do not update outside the function, unlike glob ...

Is there a way to customize Angular's number filter?

I'm trying to achieve a consistent number format with Angular's number filter, regardless of the localization selected. After inspecting the Angular source code on GitHub, I found the implementation of the filter to be like this: function number ...

Error in C due to multiple definitions in object file

There is a configuration file that defines functions and macros which I need to use. configuration.cfg #define index_zero 0 #define index_one 1 #define index_two 2 #define index_three 3   unit8 index; typedef struct {    const UINT16   f ...

Dynamic way to update the focus color of a select menu based on the model value in AngularJS

I am looking to customize the focus color of a select menu based on a model value. For example, when I choose "Product Manager", the background color changes to blue upon focusing. However, I want to alter this background color dynamically depending on th ...

Sending URL parameter to Rest API via Angular's $HTTP module

Having an issue with sending URL parameters to a rest method using an angular optimized HTML page. The code for my rest method is as follows: router.get("/url/id/:urlid",function(req,res){ var query = "SELECT urlID AS libraryid, " + ...

Manipulating custom objects with $routeParams in AngularJS

Is it feasible to assign a custom object in $routeParams during a redirect to another partial view in AngularJS with $location.path('/view2') Can this custom object then be accessed and retrieved in the controller for view2? The standard examp ...

Calculate the difference between two arrays containing objects using ES6 or TypeScript

I am faced with a challenge involving two arrays: arr1 = [{ id: 1, name: 'Diego', age: 23 }, { id: 2, name: 'Brian', age: 18 }] arr2 = [{ id: 1, name: 'Diego', ag ...

Implement a callback function to dynamically generate variables and display them within an HTML element

Apologies in advance for any errors I may make as I am a beginner when it comes to javascript, jquery, and json. I have a script that retrieves data from a json file and displays it on a webpage using javascript, jquery, ajax (I believe), and json. When ...

The true essence of Angular values only comes to light once the view has been updated

Here is the HTML code I am working with : <div class="container-fluid"> <div class="jumbotron" id="welcomehead"> <br><br><br><br><br><br><br><br><br><br> ...

Issue with AngularJS Directive: Encountering an error stating "Unexpected token"

Currently working with version 1.20 rc2 and attempting to incorporate a directive: var directives = angular.module('directives', ['controllers']); directives.directive("drink", function() { return { template: '<div>{{f ...

Detailed enrollment procedure

I am facing an issue with the code in my HTML that validates input types. The system detects empty fields and prevents proceeding to the next step. How can I disable this validation as some of the fields are not required? For instance, the input type < ...

Node.js: Extracting Querystring Parameters from an Endpoint

Trying to set up a basic node server with multiple endpoints and struggling to pass the querystring into those endpoints. Even though the endpoints are being created successfully, I'm not able to retrieve the value of the querystring in the endpoint. ...

Tips for integrating real-time view updates in AngularJs whenever the database undergoes a change

Currently, I am integrating AngularJs with the Grails framework and utilizing MySQL as the database. My goal is to create a feature that updates views automatically, similar to what happens on Facebook. Thus far, I have successfully transmitted JSON data ...