Combining the value of $(this) to create an identifier name

I am attempting to create a hover effect on an h1 element that triggers the glowing effect on a span element with an id that corresponds to the value of the h1. While I have successfully set up a glowing effect for a sentence, I am struggling to replicate it for the h1 elements. My goal is to hover over an h1 and have a square of the same color glow as a result. Can anyone provide insight into where I might be making a mistake?

$(document).ready(function() {

  $("#verb").mouseenter(function() {
    $(".verb").addClass("hovered");
  });
  $("#verb").mouseleave(function() {
    $(".verb").removeClass("hovered");
  });

  $("#noun").mouseenter(function() {
    $(".noun").addClass("hovered");
  });
  $("#noun").mouseleave(function() {
    $(".noun").removeClass("hovered");
  });


  $("h1").mouseenter(function() {
    $("#".concat($(this).val())).addClass("hovered");
  });


});
._21 {
  color: red !important
}

._106 {
  color: orange !important
}


/*glowing effect*/

#verb {
  color: blue
}

#noun {
  color: blue
}

.hovered {
  transition: text-shadow 0.1s linear;
  text-shadow: 0 0 3px blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p>
  <span id="verb">Verbs</span> &nbsp; - &nbsp; <span id="noun">Nouns</span>
</p>

I <span class="verb">like</span> 
to <span class="verb">ride</span> 
my <span class="noun">bicycle</span> 
every <span class="noun">day</span>
.
<br><br>

<h1 class="_21" value="red">
  Red
</h1>
<h1 class="_106" value="orange">
  Orange
</h1>

<p style="font-size: 28px">
  <span class="_21" id="red">■</span>
  <span class="_106" id="orange">■</span>
</p>

Answer №1

When working with strings in JavaScript, it is common to use the + operator for concatenation instead of the .concat() method. While both methods achieve the same result, using + tends to be simpler and more familiar to those reading your code. I myself had even forgotten about the existence of the .concat() method when reviewing your code!

According to the MDN page for .concat(), using + or += also provides better performance, although the difference may not be noticeable in a basic scenario like this.

In response to Patrick and Mikey's feedback, h1 elements do not have a value attribute, but you can utilize data-value as an alternative.

For a straightforward task like toggling a class on and off, consider utilizing Jquery's single-argument version of .hover(), where a single function is provided that handles both mouseenter and mouseleave events.

You can combine these suggestions into a cohesive solution as shown below:

$(document).ready(function() {

  $("#verb").hover( function() {
    $(".verb").toggleClass("hovered");
  });

  $("#noun").hover( function() {
    $(".noun").toggleClass("hovered");
  });

  $("h1").hover( function(){
    $( "#" + $(this).data('value') ).toggleClass("hovered");
  });

});
._21 {
  color: red !important
}

._106 {
  color: orange !important
}


/*glowing effect*/

#verb {
  color: blue
}

#noun {
  color: blue
}

.hovered {
  transition: text-shadow 0.1s linear;
  text-shadow: 0 0 3px blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p>
  <span id="verb">Verbs</span> &nbsp; - &nbsp; <span id="noun">Nouns</span>
</p>

I <span class="verb">like</span>
to <span class="verb">ride</span>
my <span class="noun">bicycle</span>
every <span class="noun">day</span>
.
<br><br>

<h1 class="_21" data-value="red">
  Red
</h1>
<h1 class="_106" data-value="orange">
  Orange
</h1>

<p style="font-size: 28px">
  <span class="_21" id="red">■</span>
  <span class="_106" id="orange">■</span>
</p>

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 React.js susceptible to XSS attacks through href attributes?

When user-generated links in an href tag appear as: javascript:(() => {alert('MALICIOUS CODE running on your browser')})(); This code was injected via an input field on a page that neglects to verify if URLs begin with http / https. Subseque ...

Eliminate any unnecessary spaces in the text of a link following the breaking of a word

While working on a navigation menu, I noticed that in large screens the navigation looks fine but in laptop view, the words are breaking up and it's acceptable. However, I want to remove the extra spacing after the text. In the large screen: In the ...

Error alert: TypeScript typings issue - Naming conflict with Promise / Failure to locate name Promise

I am currently working on a client/server JavaScript application and I am facing a significant issue with Promises. It appears that they are either undefined or duplicated, and this problem seems to be related to the @types package. npm install --save @ty ...

Struggling to figure out the method for obtaining css selectors for scraping in scrapy

Struggling with scraping a website and figuring out how css selectors work in Scrapy. The css in question: https://ibb.co/eJeZpb Here are some standard css selectors: .css-truncate-target .message .js-navigation-open time-ago For scrapy, you would need ...

Navigate down to the bottom of the element located on the webpage

I'm trying to create a feature where clicking an anchor tag will smoothly scroll to a specific element on the page. Currently, I am using jquery scrollTo for this purpose. Here's the code snippet: $.scrollTo( this.hash, 1500, { easing:&apos ...

Configuring JSON in PHP and JavaScript

Although I have already asked this question before, I am experiencing some issues in my code. I know that utilizing JSON is necessary and after researching multiple sources, I grasp the concept but somehow am unable to implement it correctly. Here is my co ...

Checkbox failing to trigger

Check out my code snippet here: http://jsfiddle.net/raficsaza/mgukxouj/ I'm facing an issue with the checkbox in this code. It seems to be stuck at a false value and I can't get it to change. Is there a way to work with the "input" tag instead o ...

The error message "Type 'string | number' is not assignable to type 'number'" indicates a type mismatch in the code, where a value can be either

I encountered an error code while working with AngularJS to create a countdown timer. Can someone please assist me? //Rounding the remainders obtained above to the nearest whole number intervalinsecond = (intervalinsecond < 10) ? "0" + intervalinseco ...

Material UI Grid Items not stretching to fill the entire available width

I'm currently working with a nested Grid system in Material UI, but the Grid items are only occupying a fixed width and leaving some empty space. The issue arises when this fixed space is used up and instead of adjusting their internal free space, the ...

Resolving the Table Issue with 'onclick' in Javascript

Apologies for the lack of creativity in the title, I struggled to come up with something fitting. Currently, I am engaged in the development of a user-friendly WYSIWYG site builder. However, I have encountered an obstacle along the way. I've devised ...

What is the process of sending a file from a remote URL as a GET response in a Node.js Express application?

Situation: I am working on a Multi-tier Node.js application with Express. The front end is hosted on an Azure website, and the back end data is retrieved from Parse. I have created a GET endpoint and I want the user to be able to download a file. If the f ...

variations in menu functionality on firefox

Could you please take a look at the links below? It appears that there may be an issue with FireFox. The green top menu seems to be displaying incorrectly. In Chrome/IE, it appears in one line, but in FF, the last two links are on the second line despite s ...

Navigate the conversation within the dialog without affecting the content below

Is it possible to have a dialog with scrollable content on top of a page that is also scrollable, but when trying to scroll inside the dialog using the mouse wheel, only the dialog body scrolls and not the page below it? What approach can be used to accom ...

Apply a CSS class when the tab key is pressed by the user

Currently in my Angular 14 project, I am working on a feature where I need to apply "display: block" to an element once the user reaches it using the tab key. However, I am struggling with removing the "display: block" when the user tabs out of the element ...

Using AngularJS to auto-populate additional fields after selecting an option from the typeahead autocomplete feature

Just starting with AngularJS and finally figured out how to implement Auto-complete in Angularjs. Now, when a user selects a value from the auto-complete, I want other fields to be populated based on that selection. For example, upon loading the screen, d ...

Prevent the cascading of CSS styles on child list items

When constructing my menu, I have organized it using the following HTML structure: <div id=”navigation”> <ul> <li class=”level1”>Top Level Menu item <div class=”sublevel”> <ul> ...

The PHP-generated table is not being appended to the specified div with jQuery

I am currently working on developing a webpage that displays live forex rates to users. I am pulling the values from a feed and echoing them into a table. My goal now is to use jQuery to show this table to the user. The issue I am facing is that when I tr ...

Challenges of Using Flexbox in Media Queries

How can I use flex boxes in CSS to ensure that from a min-width of 769px to 1025px, the third figure is displayed on a new line while the first and second figures remain on the top line taking up equal space? <div class="mid-col-section-2"> <figu ...

When retrieving the card in React, only the first element is affected by the .map function

There seems to be an issue with Arrays.map as it is only working for the first object in the array. Here is the main function: function App(){ return ( <div> <NavBar /> { data.map((prop) =&g ...

The art of defining PropTypes for the style attribute in Reactjs

Is there a way to pass the 'style' attribute into my component using JSX syntax? <InputTextWithValidation id="name" style={{width:'100%'}} .../> I'm wondering how I should define the PropTypes for ...