Tips for creating multiple functions within a single JavaScript function

Is there a way to combine these two similar functions into one in order to compress the JavaScript code? They both serve the same purpose but target different CSS classes. The goal is to highlight different images when hovering over specific list items - each list item corresponds to a different image.

$(".class1").mouseenter(function () {
    $(".class2").addClass("highlight");
});

$(".class3").mouseenter(function () {
    $(".class4").addClass("highlight");
});

Answer №1

  1. Assign a shared class to all the relevant elements and then apply an event listener to that common class.
  2. Utilize the data-* attribute to save the selector of the element where the class highlight should be included.
  3. Access the selector from the data attribute to execute operations on it.

Javascript:

$('.customClass').mouseenter(function() {
    $($(this).data('target')).addClass('highlight');
});

Also, include the data-target attribute in your HTML code.

<div data-target=".element2" class="element1 customClass">Lorem</div>
<!-- ^^^^^^^^^^^^^^^^^^^                ^^^^^^^          -->
<div data-target=".element3" class="element2 customClass">Ipsum</div>

Answer №2

If you're looking for a solution, consider the snippet below; however, it might be beneficial to review your CSS hierarchy as recommended by @Tushar!

[['.item1', '.item2'], ['.item3', '.item4']].forEach(function(item) {
    $(item[0]).hover(function(event) {
        $(item[1]).addClass("active"); 
    });
});

Answer №3

Building on the solution provided by @Tushar, you can easily assign multiple class attributes to an element using a comma-separated list like this:

Simply add a custom data-* attribute (where * represents any value) such as to to your elements as shown below:

<div data-to=".class2" class="class1">First Class</div>
<div data-to=".class3" class="class2">Second Class</div>

Then, with JavaScript:

$(".class1,.class2").mouseenter(function(){
    $($(this).data('to')).addClass("highlight"); 
});

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

Run a PHP function using <button onclick=""> tag

Is it possible to trigger the execution of a PHP script when clicking an HTML button? I am aware that simply calling a PHP function directly from the button's onclick event like this: <button onclick="myPhpFunction("testString")">Button</butt ...

transform array elements into an object

I encountered the following code snippet: const calcRowCssClasses = (<string[]>context.dataItem.cssClasses).map( (cssClass) => { return { [cssClass]: true }; } ); This code block generates an array of objects like ...

The ejs file is failing to load the css file

I'm facing an issue where my layout.ejs file is not loading the style.css file. I've been searching endlessly for a solution, trying various fixes and meticulously checking for typos. Despite the correct path shown in the network tab when inspect ...

What is the best way to acquire the href value from this source?

Looking to extract the dynamic value "3 Sent" from the html snippet provided. How can this be achieved? <ul class="nav nav-tabs some-tabs"> <li class="active"> <a href="#accepted" data-toggle="tab">1 Accepted</ ...

Error handling ajax and php in the submitHandler of $.validate

I encountered an issue with my double form utilizing jQuery Validate. Whenever the ajax call is supposed to execute, I receive an error message: $.validate.submitHandrer in main.js. Here is a snippet of my code: 'use strict'; // Code goes here ...

Waiting for the code to execute once the filtering process is completed in Next.js using Javascript

I'm seeking a way to ensure that my code waits for the completion of my filter function before proceeding. The issue arises because my filter function, which incorporates another function called useLocalCompare, causes a delay in execution. This delay ...

The Angular service encounters issues when interacting with REST API

Within my application, a template is utilized: <div class="skills-filter-input" ng-class="{'hidden-xs': skillsFilterHidden}"> <input type="text" ng-model="skillQuery" ng-change="filterSkills()" placeholder="Filter skills" class="filter- ...

the order of initialization in angularjs directives with templateUrl

In my current scenario, I am faced with a situation where I need to broadcast an event from one controller and have another directive's controller receive the message. The problem arises because the event is sent immediately upon startup of the contro ...

What is the best way to extend an inline-block element to cover the entire text line?

Let's talk about the scenario: https://i.stack.imgur.com/we05U.png In the image, there is a container (displayed as a div) with only one child - a span element. The goal is to introduce a second child that occupies the entire red space depicted in t ...

Troubleshooting Vue v-for loop triggering click events on multiple items simultaneously

After conducting a thorough search, I haven't found a suitable answer for my issue. The problem I am facing involves a v-for loop with buttons on each item, using VueClipboard2 to copy text. Whenever a button is clicked, some CSS changes are applied t ...

Tips on avoiding the repetition of jQuery functions in AJAX responses and ensuring the effectiveness of jQuery features

My HTML form initially contains only one <div>. I am using an AJAX function to append more <div> elements dynamically. However, the JavaScript functionality that works on the static content upon page load does not work for the dynamically added ...

Error: Unable to locate module 'child_process' in the context of NextJS + Nightmare

Encountering an issue while trying to compile a basic example using Next JS + Nightmare Scraper. Upon attempting to access the page, I am faced with the following error message, and the page fails to load. PS C:\Users\lucas\Documents\Pr ...

Ways to transfer information from a function within one element to another element

I have two components: one that logs the indexes of a carousel and I need to pass these indexes into the second component. First Component <template> <div class="container container--white"> <Header /> <carousel-3d @a ...

Utilizing BackboneJs to Access and Fetch Data from an asmx Webservice

Could someone please help me with a code snippet to understand how to call asmx web services from a backbone collection? The provided example is very simple. Collection window["Persons"] = Backbone.Collection.extend({ model: Person, url: ...

Launching ExpressJS and ReactJS on Heroku

Currently working on a project that combines express and react. When attempting to deploy it to Heroku via git push, I encountered an error upon checking the heroku logs. The specified webpage then shows a message indicating that it cannot locate a build ...

Refreshing the page when the button is clicked to upload files using AJAX

I have created a form and I need to send a file along with some other information via Ajax to a PHP file. The issue I am facing is that when I attempt to upload the file, the page refreshes after clicking on submit. How can I prevent this page refresh? Ad ...

Introduction to the CodeIgniter wkhtmltopdf library

Seeking assistance here - I am attempting to generate a printable pdf report for a calendar using Codeigniter and the fullcalendar jquery library. I have previously used mpdf successfully for creating pdf reports, but when applied to my calendar page, it ...

Is there a way to transfer the jQuery code I've developed on jsfiddle to my website?

I am currently developing a website for fun, using HTML and CSS. While I have some familiarity with these languages, I have never worked with jQuery before. However, for one specific page on the site, I wanted to incorporate "linked sliders," which I disco ...

Discovering a method to detect clicks outside of a React functional component

Looking to identify when a click occurs outside of a React functional component. After stumbling upon an article, I followed the provided code but unfortunately, it didn't work as expected. Despite identifying the issue, I am still searching for a so ...

Excessive gap located above the section element

On the web page I'm practicing with, I've noticed an unwanted space at the top of the "Favorite Food" section. To center my unordered list, I made the "section" elements inline-block, but this created the issue. How can I remove that space at the ...