Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change color of letter on mouse hover in JavaScript

This is my code:

$(document).ready(function(){
  var letters = $('p').text();
  for(var letter of letters) {
    $(letter).wrap("<span class='x'></span>");
  }
})
.x:hover {
  color: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<p>Hello World!</p>

For example, I want when hovering on r, the color of r to be orange and no other letters.

like image 518
Ehsan Avatar asked May 19 '18 07:05

Ehsan


People also ask

How do I change the color of my mouse hover?

If you want to change the link color when moving the mouse over a link, you only need the A:hover line. hover - The hover option is the color that the text changes to when the mouse is over the link. In this example, the link changes to a blue color when a mouse cursor is hovering over a link.


2 Answers

You can wrap every letter with a span with class x for example.

Example:

$("#x").html(
  $("#x").text().split("").map(a => `<span class="x">${a}</span>`)
)
.x:hover {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<p id="x">Hello World!</p>
like image 34
Mohamed Abbas Avatar answered Sep 18 '22 13:09

Mohamed Abbas


You can first create a new HTML content using <span class='x'> for each character in <p> and then replace the HTML of <p> with that HTML. Now, when you hover over each character then the color of that character changes to orange

$(document).ready(function(){
  var letters = $('p').text();
  var nHTML = '';
  for(var letter of letters) {
    nHTML+="<span class='x'>"+letter+"</span>";
  }
  $('p').html(nHTML);
})
.x:hover {
  color: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<p>Hello World!</p>
like image 60
Ankit Agarwal Avatar answered Sep 18 '22 13:09

Ankit Agarwal