1

I'm trying to highlight text in realtime using JQuery or Javascript. Current code doesn't want to search from .filters-no-actions block.

How it should look like:

enter image description here

Note: I don't want to add new text to the .filters-no-actions block, but only find text in this block using input value and highlight them.

CSS

.highlight_y {
  background-color: yellow;
}
p, div {
 display: inline-block;
}

HTML

<input id="ue__searchInput" placeholder="Search">

<div class="filters-no-actions">
  <p>Example text to search</p>
  <p>Lorem ipsum and...</p>
</div>

Script

$(document).ready(function(){

  var search_input = $('#ue__searchInput');
  $(search_input).change(function(){
    var search_box = $('.filters-no-actions').text();
    var search_box_val = search_box.val();
    if (search_box_val == this.val()) {
      search_box.append('<div class="highlight_y">' + search_box_val + '</div>');
    }
  });

});
Konrad Strek
  • 71
  • 1
  • 9

2 Answers2

2

You need to use the keyup event instead of the change event. Here is how you can do it:

$(document).ready(function(){

      var search_input = $('#ue__searchInput');
      $(document).on('keyup', '#ue__searchInput',function(){
        var search_box = $('.filters-no-actions').text();
        var search_box_val = search_input.val();
        if (search_input.val() != '') {
          $('.highlight_y').html('<p class="highlight_text">' + search_input.val() + '</p>');
        }
        else
        {
          $('.highlight_y').html('');
        }
      });

    });
.highlight_y {
  background-color: yellow;
}
p, div {
 display: inline-block;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <script src="https://code.jquery.com/jquery-2.2.4.js"></script>

</head>

<body>

    
 <input id="ue__searchInput" placeholder="Search">
 <div class="highlight_y"></div>
  <div class="filters-no-actions">
    <p>Example text to search</p>
    <p>Lorem ipsum and...</p>
  </div>


</body>

</html>
Santu Roy
  • 197
  • 7
  • Your code add new text to thix box and this is not related to my question. My point is to find text from box based on input value and highlight them in this box. – Konrad Strek Oct 27 '18 at 17:26
  • 1
    Ok, for that you can take a look on jQuery highlight plugin – Santu Roy Oct 27 '18 at 17:40
1

As Santu Roy said (+1 for him) you could try a jQuery highlight plugin like this: http://bartaz.github.io/sandbox.js/jquery.highlight.html.

In this exemple, I used it in a small delay function that is trigger after 100ms (you can change this time) your last keyup [thanks to Ata ul Mustafa for this solution: How to trigger an event in input text after I stop typing/writing? +1 also for him].

Try it:

/* This is the plugin. Put it in an external file 
=> https://github.com/bartaz/sandbox.js/blob/master/jquery.highlight.js

Here you can find all the documentation: http://bartaz.github.io/sandbox.js/jquery.highlight.html

*/

jQuery.extend({
    highlight: function (node, re, nodeName, className) {
        if (node.nodeType === 3) {
            var match = node.data.match(re);
            if (match) {
                var highlight = document.createElement(nodeName || 'span');
                highlight.className = className || 'highlight';
                var wordNode = node.splitText(match.index);
                wordNode.splitText(match[0].length);
                var wordClone = wordNode.cloneNode(true);
                highlight.appendChild(wordClone);
                wordNode.parentNode.replaceChild(highlight, wordNode);
                return 1; //skip added node in parent
            }
        } else if ((node.nodeType === 1 && node.childNodes) && // only element nodes that have children
                !/(script|style)/i.test(node.tagName) && // ignore script and style nodes
                !(node.tagName === nodeName.toUpperCase() && node.className === className)) { // skip if already highlighted
            for (var i = 0; i < node.childNodes.length; i++) {
                i += jQuery.highlight(node.childNodes[i], re, nodeName, className);
            }
        }
        return 0;
    }
});

jQuery.fn.unhighlight = function (options) {
    var settings = { className: 'highlight', element: 'span' };
    jQuery.extend(settings, options);

    return this.find(settings.element + "." + settings.className).each(function () {
        var parent = this.parentNode;
        parent.replaceChild(this.firstChild, this);
        parent.normalize();
    }).end();
};

jQuery.fn.highlight = function (words, options) {
    var settings = { className: 'highlight', element: 'span', caseSensitive: false, wordsOnly: false };
    jQuery.extend(settings, options);
    
    if (words.constructor === String) {
        words = [words];
    }
    words = jQuery.grep(words, function(word, i){
      return word != '';
    });
    words = jQuery.map(words, function(word, i) {
      return word.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
    });
    if (words.length == 0) { return this; };

    var flag = settings.caseSensitive ? "" : "i";
    var pattern = "(" + words.join("|") + ")";
    if (settings.wordsOnly) {
        pattern = "\\b" + pattern + "\\b";
    }
    var re = new RegExp(pattern, flag);
    
    return this.each(function () {
        jQuery.highlight(this, re, settings.element, settings.className);
    });
};












$(document).ready(function(){
  var delay = (function(){
    var timer = 0;
    return function(callback, ms){
    clearTimeout (timer);
    timer = setTimeout(callback, ms);
   };
  })();

  var search_input = $('#ue__searchInput');

  $(search_input).on('keyup',function(){

    delay(function(){
        $(".filters-no-actions").unhighlight({ className: 'highlight_y'}); /*remove all highlight before create a new one */
        $(".filters-no-actions").highlight($(search_input).val(), { className: 'highlight_y'});
    }, 100 );
  });

});
.highlight_y {
    background-color: #FFFF88;
}
p, div {
 display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="ue__searchInput" placeholder="Search">
<div class="highlight_y"></div>
<div class="filters-no-actions">
  <p>Example text to search</p>
  <p>Lorem ipsum and...</p>
</div>
ReSedano
  • 4,970
  • 2
  • 18
  • 31