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

The success function within the Ajax code is malfunctioning

I am currently utilizing express, node.js, and MySQL. The issue I am facing is that the success function inside my Ajax code is not working as expected. Below is the snippet of the Ajax code in question: function GetData_1(){ var state = $("#dpState_1"). ...

React Chart.js allows for consistent spacing for x-axes by displaying dates in a well-organized

After incorporating displayFormats in scales.x, I noticed that my xAxes labels are spaced differently based on the data object they contain. How can I adjust my xAxes labels to have equal spacing? The code snippet is displayed in the following image. Pleas ...

Exploring the nuances of developing React components

I've noticed that there are two common ways of creating a component import React from 'react'; class Alpha extends React.Component { render(){ ... } } or import React, { Component } from 'react'; class Alpha extends Com ...

Issue with cancelling a file upload is not functioning properly on Internet Explorer

My experience with file uploads in Internet Explorer is causing some issues. While other browsers work smoothly when canceling file uploads, Internet Explorer seems to have a different behavior. In other browsers, clicking the "Cancel" button during a fil ...

Utilize Haxe Macros to swap out the term "function" with "async function."

When I convert haxe to JavaScript, I need to make its methods asynchronous. Here is the original Haxe code: @:expose class Main implements IAsync { static function main() { trace("test"); } static function testAwait() { ...

What is the best way to include and control persistent URL parameters when making Ajax requests?

Imagine having two different resource lists on your website: one for users and the other for groups. As you navigate through each list in increments of 10, it's important to preserve the state of the list so that when you share the URL with someone el ...

The functionality of remotely accessing autocomplete in Angucomplete Alt is currently not functioning properly

I'm currently experimenting with AngularJS autocomplete using Angucomplete Alt. I've copied the same code and running it on my local host, but unfortunately, no results are being displayed. When searching for the term 'ssss', an error ...

Retrieve text from a dropdown menu while excluding any numerical values with the help of jQuery

I am currently implementing a Bootstrap dropdown menu along with jQuery to update the default <span class="selected">All</span> with the text of the selected item by the user. However, my objective is to display only the text of the selected it ...

When extracting information from a table within a Vue.js and Vuetify.js function

When trying to display a table, only one row is being printed. How can I resolve this issue? I have attempted various solutions (Vanilla JS worked). This project is for educational purposes and I am relatively new to JS and Vue.js. <template> < ...

Is it possible to execute ng-repeat on-click when ng-show evaluates to true?

I am currently facing an issue with my table that populates using ng-repeat. The table contains 100 rows, and clicking on any row reveals a new table (using ng-show) with more detailed product information. However, the performance of my web app is being af ...

Sharing information between External JavaScript and React JS/Redux

Incorporating React-redux into an externalJs application (built on a custom JS framework) has posed a challenge for me. I am trying to initialize data for the Redux store from externalJS, but it seems that the external script is unable to access the React ...

Retrieve JSON information from a document through JavaScript

Is it possible to fetch JSON data using JavaScript without relying on jQuery? I am only interested in retrieving data using pure JavaScript. Here is an example of my JSON file: {"JsonProjectIDResult":[{"_capacity":15,"_description":"Meeting Room","_dev_d ...

Correct placement of elements using absolute positioning and optimized scroll functionality

I am currently working on implementing tooltips for items within a scrollable list. My goals for the tooltips are as follows: Ensure they are visible outside and not restricted by the scroll area Appear immediately after the corresponding item Be detach ...

Having trouble locating the OBJ file in your Three.js WebGL project?

I am attempting to load an obj file using Three.js, but despite following various tutorials and resources online, I am only met with a black screen and no error messages in the console. The console output from the LoadingManager indicates that the objects ...

The state of readiness is consistently at 1, while the status remains unknown

Could someone please explain why my readyState is 1 and status is undefined in the code snippet below? $(document).ready(function(){ $('.delsub').on('submit', function (event){ event.preventDefault(); var xhr = $.aj ...

Tips for retrieving response from AJAX data array in Highcharts

I'm facing an issue while trying to retrieve JSON data using AJAX. I keep encountering the following error message: Uncaught TypeError: Cannot read property '0' of undefined. Below is an example of my simple chart data: <script type="te ...

What is the method for incorporating this effect into the final sentence of a text?

I am trying to create a unique design effect by applying a custom border to only the last line of text. You can see an example here. In this scenario, the target text is "2000 years old." (with that specific length) and not the entire width of the parent ...

Mastering the art of column stacking with CSS on your WordPress website

Looking for a CSS solution to adjust the layout when the screen resolution is lowered. Currently, I have two rows with three columns in each row, containing blurbs. My goal is to make these two rows convert into three rows with two columns each at a cert ...

Retrieve the URL of the previously visited webpage using Javascript

Is there a way to retrieve the URL of the last visited page using JavaScript? I want to be able to track which product the user viewed most recently. I have attempted the following code: var x = document.referrer; document.getElementById("demo").innerHTML ...

sending parameters to a callback function that is listening for arguments

function setmclisten(message, sender, sendResponse) { console.log(data); if(message['type'] === 'startUp') { console.log(data); sendResponse(data) } } function QuarryToServer(){ chrome.runtime.onMessage.removeListener( ...