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

Implementing a NestJs application on a microcomputer like a Raspberry Pi or equivalent device

I'm facing a challenge in trying to find a solution for what seems like a simple task. I am aware that using the Nest CLI, I can utilize the command "nest build" to generate a dist folder containing the production files of my project. However, when I ...

Learn to Generate a Mathematical Quiz with Javascript

For a school project, I am tasked with developing a Math Quiz which showcases questions one at a time. The questions vary in type, including Multiple Choice, Narrative Response, Image Selection, Fill in the blank, and more. I require assistance in creatin ...

When clicking on an item in the wishlist, only the text for that specific item should change,

Hi all, I'm in need of some assistance. I have successfully created a wishlist toggle where clicking on the heart icon changes it from an outline to solid. However, my issue lies in changing the tooltip text from "add to wish list" to "added to wish l ...

How can you make the table rows in jQuery scroll automatically while keeping the table header fixed in

Many solutions exist for making the header fixed and the table scrollable using code samples or plugins. However, my specific goal is to have the table data rows scroll automatically once they are loaded while keeping the header fixed in place. Is there a ...

Creating visualizations by overlaying shapes onto images using specified coordinates in jQuery

I have a web application in development that integrates with the skybiometry API. Their demo showcases a fantastic user feedback system displayed after facial recognition, similar to the one shown below. I am currently working on implementing a similar fe ...

Using for loop in AJAX Done() function

I'm currently working on a for loop that loops through an array consisting of 3 different report numbers. For each value in the array, an AJAX request is sent out. What I want to achieve is having a unique behavior for the .done() function based on th ...

What is the best way to capitalize the first letter of a string in JavaScript?

Is there a way to capitalize only the first letter of a string if it's a letter, without changing the case of any other letters? For example: "this is a test" → "This is a test" "the Eiffel Tower" → "The Eiffel ...

Acquiring row data upon checkbox selection: A step-by-step guide

I'm struggling to separate and assign the values returned by a function to different parameters. function saveTaxes() { $('input[type=checkbox]').each(function() { if ($(this).is(':checked')) { //test console.log ...

Guide for positioning all navbar items except one to the left, beginning at the left edge, utilizing a set minimum and maximum width, while moving the final item to the right edge

Is there a way to align all items in a navbar except for one to the left, with a fixed combined minimum and maximum width of 300px-400px, while sending the last item to the right margin? I want the final result to resemble this: https://i.stack.imgur.com ...

What are some strategies for improving the speed and efficiency of traversing an XML file with AJAX?

I am currently working with an XML file structured like this: <UUT> <DKBFile>091750</DKBFile> <part> <name>FL_U1</name> <xcoord>439</xcoord> <ycoord>132</ycoord> <width>55</width ...

Creating a consolidated HTML table by extracting and comparing data from various JSON files

Being new to JS and JSON, I am struggling to find a suitable solution that works for me. I have two distinct json files. The first one: players.json contains the following data: { "players": [ { "id": 109191123, "surnam ...

Tips on positioning images to the left and right without causing text to wrap around them

I have successfully floated an image to the left of text with the following CSS. How can I achieve a similar effect with an image to the right of text on the same page? Do I need to use a clearfix between the left and right images? Thank you! .innercont ...

Implementing a feature to dynamically add multiple markers on Google Maps

Currently, I am utilizing the .text() method to extract latng from the html. <div class="latlng"> -33.91722, 151.23064</div> <div class="latlng"> -32.81620, 151.11313</div> As a result, I am using $(latlng).text() to retrieve the ...

I am facing issues with getting the delete function to properly function in my React

Issue with Delete Button Functionality in React While I am able to successfully delete an item using axios call in Postman, implementing the same functionality on the front-end in a React component seems to be causing problems for me. <button onSubmit ...

Use Jquery to retrieve the innerhtml content

Hey there! I'm currently in the process of learning Jquery and have encountered an issue with accessing form elements. My script is designed to open a div and then fill it with a predefined HTML form. To achieve this, I'm using ajax to fetch the ...

Struggling with CSS issues in ASP.NET 4.6

For the past few months, I've been diligently working on a project that suddenly hit a snag today. Upon inspecting my website, I noticed that all my button sizes appear to be uniform. I typically use Chrome's developer tools to troubleshoot my we ...

Hovering over a dropdown menu results in the color not completely filling the background of the desired element

.nav-main { background-color:#09F; width:100%; height:100px; color:#FFF; line-height:40px; } .nav-main .logo{ float:left; padding: 40px 5px; font-size:1.4em; line-height: 20px; } .nav-main > ul { margin:0; ...

I'm wondering why my positive numbers aren't displayed in green and negative numbers in red

I am currently working on a commodities quotes widget. I have already set up the 'Current' and '24-hour' divs, but I'm facing an issue where positive values are not displaying in green and negatives in red as intended. I have check ...

The div element disappears upon calling the load() function

Currently, I am working to implement sorting criteria (such as by price or author) on my jsp page. I am utilizing ajax to refresh the content of a div when a new sorting option is selected. However, upon calling the reload function, the div just disappears ...

Bootstrap component malfunctioning and not performing as expected

Currently, I am learning how to use Bootstrap and attempting to replicate the example themes found on their official website. The specific theme I am focusing on is available at this link: https://getbootstrap.com/docs/4.3/examples/pricing/ Unfortunately, ...