Home > Software design >  Highlight an individual character of text block containing links and heading on mouse hover
Highlight an individual character of text block containing links and heading on mouse hover

Time:12-12

I am trying to achieve that when hovering over a character, the character should change color. It should work on individual characters, links, headings etc.

My following code gives me result that I want but it removes the links and headings.

$cont = $('.words');
parts = $.map($cont.text().split(''), function(v) {
  return $('<span />', {
    text: v
  });
});
$cont.empty().append(parts);
.words span:hover {
  color: #F00
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div >
  Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.
  <a href="#link">LINK</a>
  <h1>
    Heading
  </h1>
  Stet clita kasd gubergren, no sea takimata sanctus e Lorem ipsum dolor sit amet.
</div>

JS Fiddle: http://jsfiddle.net/bvpodc6z/1/

CodePudding user response:

Just map the characters separately for each text node so that it doesn't erase your DOM structure.

$('.words, .words *').contents().each(function() {
    if (this.nodeType == 3)
      $(this).replaceWith(escapeHTML(this.nodeValue).split('').map(c => `<span>${c}</span>`).join(''));
});

function escapeHTML(s) {
  return s.replace(/&/g, "&amp;")
          .replace(/</g, "&lt;")
          .replace(/>/g, "&gt;")
          .replace(/"/g, "&quot;")
          .replace(/'/g, "&#039;");
}

CodePudding user response:

Had to make some slight changes to html, namely adding a p tag around text thats not in heading or link : http://jsfiddle.net/kfbaz3gw/

$('.words').children().each( (index, el) => {
    $(el).html(function (i, html) {
      var chars = $.trim(html).split("");
      return  chars.map(c=>'<span>' c '</span>').join('')
  });
 })
  • Related