How can I improve my current code for linking 3 text elements to specific divs when hovered? The code below is functioning, but I'm looking for a more efficient script

Learning jQuery can be a slow process for beginners, but with practice and dedication, it gets easier.

I have 3 text elements in separate divs that I want to trigger the addClass function on another div when hovered over.

Although my current code works, it is not very efficient. Can someone suggest a better way to achieve this and explain the functionality of each script?

You can view the code on JSFiddle here: http://jsfiddle.net/gavAusWeb/ZYVKM/

Here is the HTML code snippet:

    <div id="sideMap">
    ...
</code></pre>

<p>And the corresponding CSS code:</p>

<pre><code>#sideMap {
    height:236px;
    
}
...

});​

JQuery code section:

$(document).ready(function() {

/*---------------------*/
$(function() {
    ...  
});
/*---------------------*/

/*---------------------*/
$(function() {
   ...
});
/*---------------------*/

});​

Answer №1

If you want to simplify your code and avoid repetition, consider the following approach:

$('.iconText').hover(function(){
    var num = this.id.match(/\d+/); // Extract the number from ID
    $('#jq_icon' + num).toggleClass('hoverMap');
});

$('.jq_icon').hover(function(){
    var num = this.id.match(/\d+/);
    $('#iconText' + num).toggleClass('iconTextHov');
});

Alternatively, you could also achieve this using index(), but given the current structure of your HTML, it may be easier to clean up first. Consider wrapping all your .iconText divs within a container for smoother implementation. Additionally, consider using h1 instead of div for better semantic correctness in this context.

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

What is the process for generating and parsing an XML file using jQuery?

I've come across a lot of information on creating and sending XML files with Ajax, but I'm feeling pretty confused. My goal is to generate an XML file and send it to the server using Ajax. In return, I expect to receive another XML file. Below ...

Validating IDs by comparing them with one another. If the IDs do not match, an error message will be displayed. If they do match, the corresponding data will

Contents: Overview of the code's functionality. CODE Achievements. Bugs Expected vs. Actual Output Attempts to troubleshoot the errors 1. Overview of the Code's Functionality This system functions as a clock in and out mechanism utilizing an R ...

Performing an AJAX request using jQuery without specifying the method name in the URL

Is the Page_Load method called if only the page name is specified in the AJAX call URL? $.ajax({ type: "POST", url: "PageName.aspx", //No method name data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: fu ...

Tips for repairing damaged HTML in React employ are:- Identify the issues

I've encountered a situation where I have HTML stored as a string. After subsetting the code, I end up with something like this: <div>loremlalal..<p>dsdM</p> - that's all How can I efficiently parse this HTML to get the correct ...

Issue with color display inconsistency in webgrid across various segments

https://i.sstatic.net/UW17M.png My goal is to display section status colors in a webgrid and divide them percentage-wise, but I am facing issues with some of the rows. Here is the cshtml script for the webgrid section status: webGrid.Column(header: "Sec ...

Tips for implementing page-break-after:always within a bootstrap row?

I have a bootstrap row with a set of divs inside like this: @media print { p { page-break-after : always } } <div class = "row"> <div> data1 </div> <p> break page here </p> <div> data2 </div> <div> ...

Encountering issues when attempting to send a POST request using Rails, React, and jQuery

I am a beginner in the world of React and I'm currently working on building a Twitter-like app for practice purposes. Although I managed to successfully retrieve a list of my tweets, I have hit a roadblock when it comes to posting a new tweet using AJ ...

How can you use HTML and SVG to move just one endpoint of a line using a mouse click?

I have been exploring ways to selectively move one end of a line, but I am encountering difficulties as it keeps altering the container and ultimately redrawing the entire line. Here is a JSFiddle link for reference: https://jsfiddle.net/h2nwygu8/1/ < ...

Steps for choosing all choices in a multi-select menu without changing the order

What is the best way to choose all the options from a multiselect box using Java Script? ...

Aligning UL LI elements vertically for multi-line textORHow to vertically

I am dealing with a ul list that contains both single and multi-line li text. The issue is that the second line of the multi-line text starts at a different indentation than the first line. I need a simple solution to resolve this problem that works seaml ...

Illuminated container with shading

I'm struggling to style a box with a unique glow effect and shadow at the bottom. I've hit a roadblock in creating this particular effect. The glow effect I am aiming for is shown here: https://i.stack.imgur.com/i2va8.png My attempts to create ...

JavaScript Error: The method 'search' is not compatible with Object [object global]

Having trouble getting the 'search' function to run when the page loads, specifically encountering an error message in self.search(event). Can someone provide some guidance on how to properly call the search function upon page load? directory.vi ...

The FormValidation plugin for Bootstrap is having issues with misplaced validation icons after changing the style

Do you think there may be an issue with the FormValidation package, or am I overlooking something? Upon testing a standard Bootstrap page, such as the "Stacked Form" example from this site, the form validates and displays icons correctly. https://i.sstat ...

How come the previous sibling element appears on top when the initial sibling is set to a position of absolute?

I have encountered an issue with two sibling sections. I applied position:absolute to the first section, but the second section is overlapping it. Even after trying to use position:relative on the second section, the problem persists. https://i.stack.imgur ...

The HighChart graphs are not rendering properly within a limited div size

I have integrated a JavaScript library called Highcharts to visualize JSON data on a line graph representing stock prices. If you are unfamiliar with the terms used in this post, refer to the image linked below for clarity: https://www.highcharts.com/image ...

Guide to developing a drop-down menu using the html <select> tag in jquery and dynamically loading it with the data retrieved from an ajax request

I'm stuck on this code snippet: function getSchools(selectedReport){ $("<select id = 'schools' onChange = 'createReport(this)'></select>").insertAfter("#myList") $.ajax({ typ ...

Adding / Deleting a Row in a sequence of floated divs

I have a group of div elements arranged side by side with the float:left style as shown below: <div id="container"> <div id=0" style="float:left">> Stuff </div> <div id=1" style="float:left">> Stuff </div> < ...

Switch Button in HTML

I am trying to implement a toggle button on my website, but unfortunately it is not working properly. Here is the HTML code I am using: <html> <head> <link rel="stylesheet" type="text/css" href="style.css" media="screen"> <script typ ...

Struggling to get the HTML layout just right on my MVC 5 Razor Page with Bootstrap CSS

I am currently facing difficulties aligning elements and displaying them in the same row. I am using MVC 5 razor pages along with HTML and Bootstrap.css. Despite spending several days on it, I have only made minimal progress since I started. I will provide ...

Absolute Positioning Problem

When I attempt to insert elements as static html text, everything functions correctly. However, when I try to insert elements at runtime (using arrays of data from the server), I encounter positioning issues with absolute. Here is the simplest example to r ...