use a for loop in javascript to attach multiple elements to an event handler

I recently discovered a method to link individual elements in an array with event handlers using a for loop in jQuery.

This informative tutorial guided me in the right direction:

Now, I have delved deeper and am attempting to connect multiple elements with the same prefix in an array to event handlers in jQuery.

The following code is functional:

var menu = new Array("#power", "#services", "#cashback", "#schedule");

$(document).ready(function(){
    $(function() {
        for(var i in menu)
        {
            (function() {
                var x = menu[i];
                var y = menu[i]+'_menu';
                 $(x).hover(
                     function () {
                        $(x).css({ backgroundColor: "#000", color: "#3ABCEF"});
                        $(y).show();
                     },
                     function () {
                        $(x).css({ backgroundColor: "#333", color: "#FFF"});
                        $(y).hide();
                     }
                );
                 $(y).hover(
                     function () {
                        $(x).css({ backgroundColor: "#000", color: "#3ABCEF"});
                        $(y).show();
                     },
                     function () {
                        $(x).css({ backgroundColor: "#333", color: "#FFF"});
                        $(y).hide();
                     }
                );
            })();
        }
    }); 
});

What I really want to achieve:

var menu = new Array("#power", "#services", "#cashback", "#schedule");

$(document).ready(function(){
    $(function() {
        for(var i in menu)
        {
            (function() {
                var x = menu[i];
                var y = menu[i]+'_menu';
                 $(x,y).hover(
                     function () {
                        $(x).css({ backgroundColor: "#000", color: "#3ABCEF"});
                        $(y).show();
                     },
                     function () {
                        $(x).css({ backgroundColor: "#333", color: "#FFF"});
                        $(y).hide();
                     }
                );
            })();
        }
    }); 
});

UPDATE ::: Final implementation that works perfectly:

var menu = new Array("#power", "#services", "#cashback", "#schedule");

$(document).ready(function(){
    for(var i in menu)
    {
        (function(x, y) {
             $(x+','+y).hover(
                 function () {
                    $(x).css({ backgroundColor: "#000", color: "#3ABCEF"});
                    $(y).show();
                 },
                 function () {
                    $(x).css({ backgroundColor: "#333", color: "#FFF"});
                    $(y).hide();
                 }
            );
        })(menu[i], (menu[i] + '_menu'));
    }
});

Answer №1

Using different variable names x and y as arguments in a function

(function(a, b) {

             $(a+','+b).hover(
                 function () {
                    $(a).css({ backgroundColor: "#123", color: "#456"});
                    $(b).show();
                 },
                 function () {
                    $(a).css({ backgroundColor: "#789", color: "#ABC"});
                    $(b).hide();
                 }
            );
})(nav[i], (nav[i] + '_menu'));

Answer №2

Avoid using $ with two arguments, instead combine them into a string:

$(x + "," + y).hover(

By doing this, you will achieve the desired selector: "#power,#power_menu" and more. When you call $ with two arguments, only the first one is considered as a selector while the second one is treated as a context for selection.

Answer №3

$(menu.join(', ')).hover();

Next, within the anonymous functions triggered by hover:

var _this = $(e.target);
var id = _this.attr('id');
var secondary_elm = $('#' + id + '_menu');
secondary_elm.show();

The final outcome should resemble something like this:

             $(menu.join(', ')).hover(
                 function (e) {
                    var _this = $(e.target);
                    var id = _this.attr('id');
                    var secondary_elm = $('#' + id + '_menu');
                    secondary_elm.show();
                 },
                 function (e) {
                    var _this = $(e.target);
                    var id = _this.attr('id');
                    var secondary_elm = $('#' + id + '_menu');
                    secondary_elm.show();
                 }
            );

This approach does not account for the secondary element that is being hovered over. Without a clear understanding of the HTML structure, it may be beneficial to reassess this aspect. Handling the .hover() event can be cumbersome initially. On top of that, managing multiple elements to perform similar actions can lead to considerable confusion.

Answer №4

jQuery(function($) {

    // Include the following code snippet inside your loop:

    var $elementX = $('#element-x');
    var $elementY = $('#' + $elementX.attr('id') + '_menu');

    function mouseEnter(event) {
        var $targetElement = $(event.target);    // target element is either x or y
        $elementX.css({ backgroundColor: "#000", color: "#3ABCEF"});
        $elementY.show();
    }

    function mouseLeave(event) {
        var $this = $(event.target);    // target element is either x or y
        $elementX.css({ backgroundColor: "#333", color: "#FFF"});
        $elementY.hide();
    }

    $elementX.add($elementY).hover(mouseEnter, mouseLeave);
});

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

How can I achieve the quickest image loading speed with JavaScript?

If I have a large ecommerce website with 15,000 image elements that need to be added to the HTML, what is the best approach using JavaScript to optimize efficiency and enhance user experience? ...

Determine if the value is present in every element of the array and return true

I am looking for a way to determine if all products have the status "Done" in their respective statusLog arrays. If any product does not contain "Done" or lacks the statusLog property altogether, then the function should return false. Although the current ...

Attempting to integrate a complex Ruby operation (using each loop and iterator) into a JavaScript platform (such as Google Charts API) by creatively combining them in a non-conventional manner during the development phase

It's time for my application to transition into production mode, and I have come to the realization that some of the code in development mode needs a major overhaul. Particularly, the views where I embedded data iteratively into Google Charts API Java ...

Setting up web config values for unobtrusive validation in an MVC project

My web.config holds important values that serve as settings for my website. One example is the minimum age limit for events, which is set at 16. To implement this functionality, I have developed custom data annotations and use ConfigurationManager to retri ...

Is it possible to generate a star rating system from an image using a decimal value?

Recently, I have been eager to convert a number into a star rating and stumbled upon this helpful post here: . The post perfectly explains what I am looking to achieve. Despite following the instructions provided, I am facing difficulties getting it to fun ...

Generate various instances of the identical function with distinct variables for each occurrence within a Socket.io event

I am looking to enhance my code by creating multiple instances of the same function with various variables passed from the front end through a socket.io event. These variables should also be accessible in another socket.io event so that I can stop the func ...

"How to eliminate the hash symbol from a URL using react-router-dom in a React.js

Recently started learning react.js and running into an issue with the URL structure while using react-router-dom v6 in my project. Specifically, I'm finding a problem with the # symbol in the URL. For instance: {url}/#/dashboard I would like it to b ...

Implementing automatic pagination based on container height using jQuery

Looking to convert an AngularJS fiddle into jQuery. The goal is to create pagination using several p tags only with jQuery. Current code: <div class="parent"> <p>text1</p> <p>text2</p> <p>text3</p> ...

What is the reason for IE displaying null when the model does not exist?

Why does IE 11 render 'null' if my model does not exist? For instance: <tr> <td [innerHTML]="model?.prop1 | my-pipe"></td> </tr> Imagine this scenario: When the page loads, a request is sent to the server and the res ...

How can I add a custom column to the ajax data when using AJAX, jQuery, and the Datatables plugin?

Utilizing AJAX / PHP to fetch data into a table for display via the DataTable JS plugin. The data query functions correctly, but I want to include an additional column for each record with buttons for previewing / editing / deleting the respective record. ...

HTML anchor tag failing to redirect to specified link

I need to populate the URI property from an API result into an HTML format. I attempted to achieve this by calling a function and running a loop 3 times in order to display 3 links with the URI property of each object. However, the code is not functioning ...

How to prevent writing to the z-buffer for a specific object in Three.js

I have been attempting to prevent a write to the z-buffer for a specific object in three.js. This is what my code currently looks like: mesh.onBeforeRender = function(renderer){renderer.context.depthMask(false)}; mesh.onAfterRender = function(renderer){r ...

ensure that the radio button is selected on the contact form 7

I'm looking to customize the appearance of my radio buttons within a WP plugin ContactForm7. I found some CSS code on this website: Source CSS code My goal is to change the color of the radio button to green when it's clicked or checked: .wpcf7 ...

Introduce an additional parameter to the Prestashop Cart entity

After setting up a radiobox "stock_action" in the Cart, I need to send its value to the Cart object for additional order costs. In the Cart Override, the $stock_action variable has been added: public $stock_action; /** * @see ObjectModel::$defi ...

The attempt to connect with react-native-fetch-blob has not been successful

How do I resolve the issue of displaying a PDF from my assets folder in an Expo, React Native project using react-native-pdf? While scanning folders for symlinks, encountered an error with RNFetchBlob library in my project directory. The automatic linki ...

What steps should I take to fix an error in my code?

My current objective is to write a program that generates a square with dimensions of 200 pixels by 200 pixels. The square should be colored using specific RGB values: red (red value of 255), green (green value of 255), blue (blue value of 255), and magent ...

Why does my AJAX form continue to load my PHP page?

I am really struggling to wrap my head around AJAX and could definitely use some assistance. I found this example online, but it's not working quite like I anticipated. The form is successfully posting the data, but upon submission, the .php page is ...

Changing the $scope value in one controller based on the input from a

I'm facing an issue with updating my side menu items based on user data. I have a side menu controller where I need to display the username, and in another controller where I retrieve user data from the database and want to update the menu items accor ...

Implementing the 'keepAlive' feature in Axios with NodeJS

I've scoured through numerous sources of documentation, Stack Overflow threads, and various blog posts but I'm still unable to make the 'keepAlive' functionality work. What could I be overlooking? Here's my server setup: import ex ...

The function passport req.isAuthenticated() consistently returns false

I am currently working on implementing express session for user login functionality. My goal is to allow users to access their profile page and view their user data after logging in. However, I am facing an issue with line 9 of my routes.js file: even tho ...