Click here to Skip to main content
15,891,664 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have followed a tutorial and made a search box with search, next, previous buttons. It works, but I would like to make the web page scroll automatically when pressing search, next and previous, according to where the text is located. Are there any tutorials that can help me achieve this?

What I have tried:

<script
  src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
  integrity="sha256-3edrmyuQ0w65f8gfBsqowzjJe2iM6n0nKciPUp8y+7E="
  crossorigin="anonymous"></script>

<pre>
<div class="SearchButtonsSection">
        
          <input name="text-12" id="text-12" value="" type="text" class="txtSearch">
          <button><a href="#" class="search btn">Search</a></button>
          <button><a href="#" class="next btn">Next</a></button>
          <button><a href="#" class="previous btn">Previous</a></button>
    </div>

        <div id="content" style="with:100%">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed in felis ut dui dictum cursus. In at congue dui. Fusce sit amet ligula faucibus, tincidunt ligula nec, elementum dolor. Integer dignissim tellus vitae ligula egestas, laoreet dictum mauris laoreet. Nulla lorem turpis, hendrerit quis urna ut, bibendum hendrerit elit. Sed non lorem tincidunt, viverra purus fringilla, dignissim mauris. Phasellus ac pellentesque enim. Fusce et mattis nibh. Maecenas non imperdiet nisi, lobortis consequat mauris. Etiam suscipit odio vitae interdum cursus. Aliquam ut rhoncus metus. Donec sed malesuada augue, eu interdum orci. Vestibulum porta lobortis orci a maximus. Etiam id tellus eleifend, condimentum nisi ac, lobortis ante. Nullam nec libero porttitor, dictum lacus sit amet, faucibus nulla.

Maecenas scelerisque posuere sem sed auctor. Ut eget dapibus diam, molestie eleifend est. In interdum lacus vitae ullamcorper convallis. Sed nec felis vitae lacus rhoncus suscipit commodo eget diam. Phasellus tincidunt, turpis vel ultricies cursus, massa est egestas mi, ut faucibus velit neque nec dui. Suspendisse potenti. Phasellus rhoncus, felis a sagittis condimentum, quam purus mattis urna, id ullamcorper dui mauris id nisl. Donec bibendum a nunc at hendrerit. In porttitor turpis at lorem tincidunt venenatis. Mauris mattis dolor sed libero iaculis, quis mattis dui ornare. Nullam euismod, metus vel blandit viverra, ipsum elit fermentum felis, eu facilisis nisi mi non nisl. Integer enim erat, feugiat eget consectetur non, dapibus id nisi </p></div>


<style>

 .highlighted {
     background-color:yellow;
 }
 .highlight {
     background-color: #fff34d;
     -moz-border-radius: 5px;
     /* FF1+ */
     -webkit-border-radius: 5px;
     /* Saf3-4 */
     border-radius: 5px;
     /* Opera 10.5, IE 9, Saf5, Chrome */
     -moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.7);
     /* FF3.5+ */
     -webkit-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.7);
     /* Saf3.0+, Chrome */
     box-shadow: 0 1px 4px rgba(0, 0, 0, 0.7);
     /* Opera 10.5+, IE 9.0 */
 }
 .highlight {
     padding:1px 4px;
     margin:0 -4px;
 }
    
    .searchBtns{
        height:20px;
        width:100px;
        border: 1px solid black;
        float:left;
        margin-bottom: 20px;
        text-decoration: none;
    }
    .SearchButtonSection{
        height:300px;
        width:100%;
        
    }
    
    a {
        text-decoration: none;
        color:black;
    }
    
    .button{
        float:right;
        margin-left:50px;
    }
</style>


<script>
function searchAndHighlight(searchTerm, selector) {
    if (searchTerm) {
        //var wholeWordOnly = new RegExp("\\g"+searchTerm+"\\g","ig"); //matches whole word only
        //var anyCharacter = new RegExp("\\g["+searchTerm+"]\\g","ig"); //matches any word with any of search chars characters
        var selector = selector || "#content"; //use body as selector if none provided
        var searchTermRegEx = new RegExp(searchTerm, "ig");
        var matches = $(selector).text().match(searchTermRegEx);
        if (matches != null && matches.length > 0) {
            $('.highlighted').removeClass('highlighted'); //Remove old search highlights  

            //Remove the previous matches
            $span = $('#content span');
            $span.replaceWith($span.html());

    if (searchTerm === "&") {
        searchTerm = "&";
        searchTermRegEx = new RegExp(searchTerm, "ig");
    }
            $(selector).html($(selector).html().replace(searchTermRegEx, "<span class='match'>" + searchTerm + "</span>"));
            $('.match:first').addClass('highlighted');

            var i = 0;

            $('.next').off('click').on('click', function () {
                i++;

                if (i >= $('.match').length) i = 0;

                $('.match').removeClass('highlighted');
                $('.match').eq(i).addClass('highlighted');
                $('.ui-mobile-viewport').animate({
                    scrollTop: $('.match').eq(i).offset().top
                }, 300);
            });
            $('.previous').off('click').on('click', function () {

                i--;

                if (i < 0) i = $('.match').length - 1;

                $('.match').removeClass('highlighted');
                $('.match').eq(i).addClass('highlighted');
                $('.ui-mobile-viewport').animate({
                    scrollTop: $('.match').eq(i).offset().top
                }, 300);
            });




            if ($('.highlighted:first').length) { //if match found, scroll to where the first one appears
                $(window).scrollTop($('.highlighted:first').position().top);
            }
            return true;
        }
    }
    return false;
}

$(document).on('click', '.search', function (event) {

    $(".highlighted").removeClass("highlighted").removeClass("match");
    if (!searchAndHighlight($('.txtSearch').val())) {
        alert("No results found");
    }


});
</script>
Posted

1 solution

 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900