Using dynamic jquery to target specific elements. How can we apply jquery to selected elements only?

Hello everyone! I have been working on a simple hover color change effect using jQuery, but I noticed that I am repeating the code for different buttons and service icons. Is there a way to achieve the same result so that when a button is hovered, the corresponding service icon changes color without repeating the code multiple times like below?

$(document).ready(function() {
    $('.btn-1').hover(function() {
        $('.service-icon-1').css('color', '#05FAB8');
    },function(){
        $('.service-icon-1').css('color', '');
    });
});
$(document).ready(function() {
    $('.btn-2').hover(function() {
        $('.service-icon-2').css('color', '#05FAB8');
    },function(){
        $('.service-icon-2').css('color', '');
    });
});
$(document).ready(function() {
    $('.btn-3').hover(function() {
        $('.service-icon-3').css('color', '#05FAB8');
    },function(){
        $('.service-icon-3').css('color', '');
    });
});

Answer №1

To ensure the relevance of my code snippet, your HTML structure is crucial. I have assumed that the icons are not direct children of each button for added complexity.

If I were to implement this using JavaScript, I would utilize a data attribute on both the button and icon elements to store the service number, then leverage this data attribute value in an attribute selector.

It's worth noting the use of template literals with backticks ` and ${}.

$(document).ready(function() {
    $('.btn').hover(function() {
        let serviceNb = $(this).data("service")
        $(`.service-icon[data-service=${serviceNb}]`).css('color', '#05FAB8');
    },function(){
        let serviceNb = $(this).data("service")
        $(`.service-icon[data-service=${serviceNb}]`).css('color', '');
    });
});
div{
  margin: 1em;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>
  <span class="service-icon" data-service="1"><i class="fa fa-tools"></i></span>
  <span class="service-icon" data-service="2"><i class="fa fa-hand-holding-usd"></i></span>
  <span class="service-icon" data-service="3"><i class="fa fa-trash"></i></span>
</div>

<button class="btn"  data-service="1">Repair</button>
<button class="btn"  data-service="2">Sell</button>
<button class="btn"  data-service="3">Trash</button>

Answer №2

1) Incorporate "btn-1", "btn-2, "btn-3" into the ID of your buttons, rather than using class.
2) Assign a common class to all buttons. (e.g. "btn")
3) Utilize $(".btn").hover ONCE
4) You can retrieve the actual ID (e.g. "btn-1") using $(this).prop("id")
5) Capture the number (e.g. "1") from the retrieved ID and store it in variable btnIdNo.
6) Apply $(`.service-icon-{btnIdNo}`).css(blah)

It is advisable to assign unique identifiers to IDs instead of using CLASS. Reserve CLASS for distinguishing different types of elements.

Answer №3

Here's a possible solution:

 $(document).ready(function() {
   $('.btn-1, .btn-2, .btn-3').on('mouseover', function() {
      if ($(this).is('.btn-1')) {
        $('.service-icon-1').css('color', '#FF5733');
      } else if ($(this).is('.btn-2')) {
        $('.service-icon-2').css('color', '#FF5733');
      } else {
        $('.service-icon-3').css('color', '#FF5733');
      }
   }).on('mouseout',function(){
      $('.service-icon-1, .service-icon-2, .service-icon-3').css('color', '');
   });
});

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 there a feature similar to Nuxt.js' auto-register in Next.js?

My Journey as a Beginner Being a beginner in the tech world, specifically in full-stack development (although I'm about 8 years behind), I find myself grappling with the decision of what to focus on learning. Vue and Nuxt.js are fantastic technologi ...

Incorporate SVG files into a TypeScript React application using Webpack

I am trying to incorporate an SVG image into a small React application built with TypeScript and bundled using Webpack. However, I am encountering an issue where the image is not displaying properly (only showing the browser's default image for when n ...

What is the best way to send a JavaScript array to a Perl script using AJAX?

Is it possible to convert a JavaScript array passed via AJAX into a Perl array? Accessing in Perl: @searchType = $cgi->param('searchType'); print @searchType[0]; Result: employee,admin,users,accounts It appears that the first value in the ...

Issue regarding custom CSS implementation in Angular project

Being a French speaker, I apologize in advance for any mistakes I might make. I am also fairly new to Angular, so if you could provide detailed explanations in your responses, it would be greatly appreciated. Thank you. I am trying to import a custom CSS ...

Effortless link to a Gremlin database using a JavaScript app

I apologize for my lack of technical knowledge, but I am struggling to solve this issue despite studying the documentation. My goal is to establish a connection with a standard Gremlin DB (Cosmos) using gremlin. While it works well from the server, encoun ...

Access the JSON data stored in the File Directory by reading and utilizing it for your project

Can someone help me figure out how to retrieve data from the xmltojson.json file and assign it to a variable using JavaScript? const jsonfile = require('jsonfile') const file = 'xmltojson.json' jsonfile.readFile(file, function (err, obj ...

Implementing various style guidelines for distinct elements

Currently, I am struggling with organizing my unordered list elements to be stacked side by side. The style rule I have been using is as follows: #slide ul,li{ float:left; list-style-type:none; } Now, I am attempting to introduce another unordered list t ...

Issue with AngularJS compatibility on first generation iPad

Having trouble with my first generation iPad while trying to implement a basic ngRoute and ngAnimate setup. It's working fine on desktop and iPhone 6, but not on the iPad. The error message I'm encountering is: Error[$injector:modulerr]http://e ...

I am looking to retrieve the body's background color using Regular Expressions

Trying to extract the background color from a CSS string: "body{ background-color: #dfdfdf; } " The color could also be in rgba(120,120,120) format. I am looking for a way to extract that color using regular expressions. I have tried using this patt ...

Pattern matching excluding "two or more" white spaces

Looking for a unique regular expression that meets the following criteria: No spaces allowed at the beginning or end of a line Only one space permitted between words The previous attempt using "^[АЯ-Ёа-яё0-9' ']+$" didn't q ...

Looking for a way to exclude both parents and children from a list of relatives? Want to ensure that the

I've been struggling to align these list elements with their counterparts, but they seem to automatically create a margin for their child elements. It is essential for these list items to maintain the position:relative attribute so that the #dropdown ...

What is the solution for fixing the Typescript error in formik onSubmit?

I encountered an error while using the onSubmit prop of Formik: The type '(values: { email: string; password: string; }) => { type: string; payload: { email: string | null; password: string | null; }; }' is not compatible with the type '(( ...

What is the best way to modify the colors of two specific elements using a combination of CSS and JavaScript

I am currently developing a browser-based game and have encountered an issue. Here is the relevant line of my HTML/PHP code: echo '<div id="div'.$n.'" class="d'.$rand.'" onclick="swapit(this.id, this.className)"></di ...

Display a div in front of another using Material UI when hovering

Is there a way to display a black transparent div in front of a <MediaCard/> when hovering over it? Below is the code snippet I am using with Material UI: <Box> <Typography variant='h3'>Home Page</Typography> < ...

What is the best way to navigate through the underlying MatDialog while the MatSelect is active?

When attempting to customize the scroll behavior of a MatSelect in a regular page, I discovered that using the MAT_SELECT_SCROLL_STRATEGY injection token with the NoopScrollStrategy allows for scrolling the underlying page while keeping the MatSelect stati ...

The art of toggling div visibility with jQuery

When a button is clicked, I want to display a div named 'info'. <button>Toggle</button> <div id="toggle"> Test </div> I'm looking to implement a jQuery sliding feature to reveal the div, but I'm unsure of where ...

Is it possible to include two of these on a single page with unique variables? (Using JQuery)

I am looking to create two similar pages, each with different percentages. However, when I try modifying the JS or changing class/ID names, it keeps pulling data from the first SPAN element. http://jsfiddle.net/K62Ra/ <div class="container"> <di ...

JavaScript event in Chrome extension triggers a browser notification and allows for modification using a specific method

I am currently developing a Chrome extension that is designed to take specific actions when system notifications appear, with the main goal being to close them automatically. One example of such a notification is the "Restore pages?" prompt: https://i.sta ...

Avoiding Scroll Reset on Browser Navigation with Delayed Transition

I've recently implemented a delay in my router configuration on my website. However, I've noticed that when I try to navigate using the browser's back and forward buttons, it first jumps to the top of the page because of the delay set with { ...

Arranging two list items (<li>) side by side in HTML code

I am currently designing a form with a side navigation bar that will display around 15-20 elements. Each element is represented by an <li> containing a link to open a modal when clicked. This is the current structure of my code: <div id="sidebar ...