Skip to main content
keyword-highlighter

Text Search and Highlight Using jQuery Mark.js and Bootstrap Modal

This jQuery tutorial help to search text into the bootstrap modal box and highlight all matched text using mark.js. I am using third-party keyword highlighter jquery plugin and modified to use into the modal box with jQuery, The main challenge is to add a scroll position in the bootstrap modal box against the highlighted keyword.

I am using jQuery version of mark.js.It’s also available as a core JavaScript plugin.The mark.js has jquery lib as dependency package which must be included before mark.js file. You can download source file from mark.js GITHUB.

Simple Example of Highlight Text Using jQuery Mark.js

I will create a simple /text_highlighter foldetr and create index.html file with in this folder.I will follow following steps to implement search and highlight text on paragraph using jQuery markjs highlighter plugin.

keyword-highlighter

Step 1: We will include all dependencies files into head section of index.html file. Since I am using Bootstrap Modal box So I will include bootstrap.css, bootstrap.js file for modal box.I will also include mark.js file to highlight text, The all dependencies files must be included into of the index.html file.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.0/jquery.mark.js"></script>

I prefer using a CDN instead of downloading the files. You can use as a local path as well.

Step 2: I will create a button into index.html file that will open bootstrap modal box on click of this button.

<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

Also Checkout other useful jQuery tutorials,

Step 3: I will create bootstrap Modal box and set default to hide.I also added some sample content into body of model box to search data.

<div id="myModal" class="modal fade" role="dialog">
    <div class="modal-dialog">
        <!-- Modal content-->

        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">×</button>

                <h4 class="modal-title">Modal Header</h4>

                <div class="header">
                    Search:
                    <input type="search" placeholder="Lorem" />
                    <button data-search="next">↓</button>
                    <button data-search="prev">↑</button>
                    <button data-search="clear">?</button>
                </div>
            </div>

            <div class="modal-body content">
                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis eu ullamcorper orci, eget porttitor justo. Aliquam id sollicitudin elit. Nulla in sodales ipsum. Donec vulputate venenatis magna. Vestibulum sit amet leo lacinia,
                cursus lectus in, gravida metus. In ultricies sed tortor non pellentesque. Mauris quis tempor neque. Donec nec sagittis magna. Integer fringilla posuere metus eu mollis. Ut ac porta metus. Duis sed lacinia metus. Nunc
                malesuada iaculis risus vitae bibendum. Maecenas auctor nec ligula ac luctus. Nam sit amet euismod mauris. Donec et diam sit amet eros efficitur tempor. Mauris non erat sit amet nunc interdum pulvinar. Sed luctus hendrerit
                justo eget pulvinar. Cras non arcu sed ligula faucibus pulvinar. Sed egestas risus nisl. Duis quis arcu tempus, cursus erat ac, gravida enim. Cras et condimentum ante. Nullam eleifend egestas velit, quis semper est imperdiet
                non. Donec quis purus varius, placerat mi et, dictum lorem. Sed quis finibus nisi, vitae molestie metus. Donec lobortis eros quis vestibulum vulputate.
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

Above code will use to display bootstrap modal box on-click of the open modal button.

Step 4: I will add some jquery code to apply mark search text into a model box and drill down on highlighted text based on prev and next button.

$(document).ready(function(){              
 
  // the input field
  var $input = $("input[type='search']"),
    // clear button
    $clearBtn = $("button[data-search='clear']"),
    // prev button
    $prevBtn = $("button[data-search='prev']"),
    // next button
    $nextBtn = $("button[data-search='next']"),
    // the context where to search
    $content = $(".content"),
    // jQuery object to save <mark> elements
    $results,
    // the class that will be appended to the current
    // focused element
    currentClass = "current",
    // top offset for the jump (the search bar)
    offsetTop = 10,
    // the current index of the focused element
    currentIndex = 0;
 
  /**
   * Jumps to the element matching the current Index
   */
  function jumpTo() {
    if ($results.length) {
      var position,
        $current = $results.eq(currentIndex);
      $results.removeClass(currentClass);
      //console.log($current.length);
      if ($current.length) {
        $current.addClass(currentClass);
                                // console.log($current.offset());
                                // console.log($current.offset().top);
                                // console.log(offsetTop);
    var modalScrollPos = $("#myModal .modal-body").scrollTop();
        position = (modalScrollPos + $(".current").position().top) - offsetTop;
 
                                //console.log($(".current").position());
    //console.log($current.offset());
    //console.log($("#myModal .modal-body").scrollTop());
    //console.log($(window).height());
    //console.log($("#myModal .modal-body").position().top);
        //window.scrollTo(0, position);
                                //console.log('ggg11');
                                $("#myModal .modal-body").scrollTop(position);
      }
    }
  }
 
  /**
   * Searches for the entered keyword in the
   * specified context on input
   */
  $input.on("input", function() {
   var searchVal = this.value;
    $content.unmark({
      done: function() {
        $content.mark(searchVal, {
          separateWordSearch: true,
          done: function() {
            $results = $content.find("mark");
            console.log($results);
            currentIndex = 0;
            jumpTo();
          }
        });
      }
    });
  });
 
  /**
   * Clears the search
   */
  $clearBtn.on("click", function() {
    $content.unmark();
    $input.val("").focus();
  });
 
  /**
   * Next and previous search jump to
   */
  $nextBtn.add($prevBtn).on("click", function() {
    if ($results.length) {
      currentIndex += $(this).is($prevBtn) ? -1 : 1;
      if (currentIndex &lt; 0) {
        currentIndex = $results.length - 1;
      }
      if (currentIndex &gt; $results.length - 1) {
        currentIndex = 0;
      }
      jumpTo();
    }
  });
  });
</mark>

As you can see, I am re-positioning the modal box scroll bar based on modal and window height.

Step 5: Finally, Added some css classes to set height of modal box into head section of index.html file.

<style>
mark {
  background: yellow;
}
 
mark.current {
  background: orange;
}
 
.header {
  padding: 10px;
  width: 100%;
  background: #eee;
  position: fixed;
  top: 0;
  left: 0;
}
 
.content {
  height:400px;
  overflow-y:scroll;
}
</style>

Conclusion:

I have implemented search string into the modal box and highlighted all matched text using markjs. I have also added vertical scroll bar and position scroll based on highlight text. You can also navigate matched text using next and prev button and moved cursor accordingly.

You can download source code and Demo from below link.

Leave a Reply

Your email address will not be published. Required fields are marked *