"Finding specific data on a list with ease - A guide to scrolling using a searchbox

One interesting feature of my project is the search box that allows users to quickly find specific data in a populated div list sourced from the database. When a user types something into the search box, the corresponding data will be scrolled to on the list. Have a fantastic day!

If you would like to see the code in action, check out the JSFIDDLE.

I've made some modifications to this question and incorporated a script into my project. Unfortunately, I'm still experiencing issues with getting the scrolling functionality to work.

$(document).ready(function() {
        $('.search-field').on('keyup blur change', function() {
            var text_s = $(this).val();

            $("li#dirlist").removeClass("highlight");

            if (text_s.length > 0){
                $("li#dirlist").each(function(){
                    var li_value = $(this).text();
                    if (li_value.indexOf(text_s) >= 0){
                        $(this).addClass("highlight");
                        var x = getOffset( document.getElementById(this.id) ).left;
                    }
                });
            }
        });
    }); 

    function getOffset( el ) {    
        var _x = 0;
        var _y = 0;
        
        while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
            _x += el.offsetLeft - el.scrollLeft;
            _y += el.offsetTop - el.scrollTop;
            el = el.offsetParent;
        }
        
        window.scrollTo(_x,_y);
        return { top: _y, left: _x };
    }       

Answer №1

Your desired content is provided below:

View the Example on JsFiddle: http://jsfiddle.net/q52Fc/1/

HTML Code Snippet:

<div class="container">
    <div class="row-fluid">
        <div class="span12">
            <div class="green-bar">
                <h4><center>Directory</center></h4>
            </div>
        </div>
    </div>
    <br>
    <br>
    <div class="span4">
        <div id="name-dir">
            <div class="row">
                <div class="control-group">
                    <div class="controls">
                        <div class="input-prepend"> <span class="add-on"><i class="icon-search"></i></span>

                            <input class="block search-field" id="inputIcon" type="text" placeholder="Search">
                        </div>
                    </div>
                </div>
            </div>
            <br>
            <div class="contact-list">
                <div class="contact-gray-bar">A</div>
                <ul class="contact">
                    <!-- insert records here -->
                    <li>Apple</li>
                    <li>Amethyst</li>
                    <li>Aratilis</li>
                </ul>
                <div class="contact-gray-bar">B</div>
                <ul class="contact">
                    <!-- insert records here -->
                    <li>Banana</li>
                </ul>
                <div class="contact-gray-bar">C</div>
                <ul class="contact">
                    <!-- insert records here -->
                    <li>Cross</li>
                    <li>Cross</li>
                    <li>Cross</li>
                    <li>Cross</li>
                    <li>Cross</li>
                    <li>Cross</li>
                    <li>Cross</li>
                    <li>Cross</li>
                    <li>Cross</li>
                    <li>Cross</li>
                    <li>Cross</li>
                    <li>Cross</li>
                    <li>Cross</li>
                    <li>Cross</li>
                </ul>
                <div class="contact-gray-bar">K</div>
                <ul class="contact">
                    <!-- insert records here -->
                    <li>Kiwi</li>
                </ul>
                <br>
            </div>
        </div>
    </div>
</div>
</div>

JavaScript Code Section:

$(function () {
    $('.search-field').on('keyup', function () {
        var first_result = false;

        var text_s = $(this).val().toLowerCase();

        //Reset li elements and scroll position to top
        $("li").removeClass("highlight");
        $(".contact-list").scrollTop($(".contact-list").position().top);

        if (text_s.length > 0) {
            $("li").each(function () {
                var li_value = $(this).text().toLowerCase();
                if (li_value.indexOf(text_s) >= 0) {
                    $(this).addClass("highlight");
                    if (first_result == false) {
                        //Scroll to the position of the first matching element
                        first_result = true;
                        $(".contact-list").scrollTop($(this).position().top);
                    }
                }
            });
        }
    });
});

CSS Style Section: no changes were made.

To further explore the topic of positioning, refer to: http://api.jquery.com/position/

Answer №2

Consider Trying This Approach

$(document).ready(function() {
    $('.search-input').on('input', function() {
        var searchValue = $(this).val();

        $("li").removeClass("highlight");

        if (searchValue.length > 0){
            $("li").each(function(){
                var liText = $(this).text();
                
                if (liText.toLowerCase().includes(searchValue.toLowerCase())){
                    $(this).addClass("highlight");
                    var offsetX = getHorizontalOffset( document.getElementById(this.id) );                    

                }
            });
        }
    });
});

function getHorizontalOffset( element ) {    
    var _left = 0;
    var _top = 0;
    while( element && !isNaN(element.offsetLeft) && !isNaN(element.offsetTop)) {
        _left += element.offsetLeft - element.scrollLeft;
        _top += element.offsetTop - element.scrollTop;
        element = element.offsetParent;
    }
    window.scrollTo(_left, _top);
    return { top: _top, left: _left };
}

VIEW DEMO

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Passport.js implementation in a Next.js application does not persist the user's login state when navigating between routes

I'm currently utilizing passport.js with the local-strategy for authentication in my next.js application. Data store requests and authentication are functioning properly. However, I need access to the req.user in another route to retrieve the users._ ...

Completing the remainder of the page with CSS styling

Currently, I have three Divs positioned absolutely on the page - leftDiv, middleDiv, and rightDiv. The middleDiv has a width of 900px, which is fine. However, I need the leftDiv and rightDiv to fill the remaining space on the left and right sides, regardle ...

Arranging an array using jQuery JSON information

I've been working on sorting an array that is generated by a PHP script. The PHP script retrieves HTML files from a directory and then utilizes jQuery to fetch and display them on the webpage. Below is a snippet of my current code: <script> $( ...

Element is not perfectly aligned with the bottom; Slightly below the bottom edge

Why does an element positioned absolutely within a div that has relative positioning end up slightly lower than the bottom of the parent div? What can be done to fix this issue without just adjusting the bottom value on .hoverAction? function showFileUp ...

The array of objects has vanished into thin air

I am receiving a JSON string from my server through a PHP file, which contains 25 meals. The PHP script is initiated by a JavaScript function. My goal is to convert the JSON into an array of objects. The response stream displays the correct values and eac ...

Leveraging the power of jQuery mobile in tandem with Rails' RESTful controller

Recently, I attempted to incorporate jQuery mobile views into a Rails 3 project and encountered some issues related to RESTful controller actions. For example, when using PUT/posts to create a new record with the Create Action, everything seems to work fin ...

Looking for a simple method to display a popover using conditional if/else statements?

On my website, I am utilizing JavaScript to determine the user's Facebook status. This includes checking if the user is already logged in and has allowed our app, if they are logged in but haven't authorized our application, or if they are not lo ...

Constantly monitoring the current window width

Is there a way to dynamically get the width of the browser as it is resized in real time? I have found a solution that provides the width, but it only updates when I refresh the page. How can I continuously update the value while resizing the browser? Thi ...

Unexpected behavior observed: Title attribute malfunctioning upon double clicking span element

I recently implemented the following code: <span title="hello">Hello</span> Under normal circumstances, the title attribute functions correctly when hovering over the element. However, after double clicking on the span element (causing the t ...

Tips for identifying modifications in an input text field and activating the save button

Currently, I am developing a function that can detect any changes made in the text field and then activate the save button accordingly. This code is being executed in Visual Studio 2017, using HTML and JavaScript. (function () { var customer_addres ...

How can tick values be displayed on a c3js line chart when all data is unselected?

I'm currently working with a c3js line chart that displays 3 different lines. However, I noticed that when I remove all data sources, the x-axis tick values disappear. Is there a way to keep the x-axis tick values visible even when there is no data pr ...

"Integrating JavaScript files into HTML using Flask: A step-by-step guide

I have created an HTML page with a JavaScript section where I am importing various other .js files: <script type="module"> import * as THREE from "../build/three.module.js"; import { OrbitControls } from ...

Exploring jasmine testing with ajax requests

I've been working on writing Jasmine unit tests for a JavaScript file that includes an Ajax call. I'm unsure how to properly test the 'Success' function using Jasmine. Here's a snippet of the code: function getGroups(){ var defe ...

What is the most effective way to populate an element using jQuery?

When you click a button with jQuery, I am generating a modal (Bootstrap modal) as a string. This modal has two option classes: Call Today and Call Tomorrow, which seems fine so far. Upon clicking the button, the modal is created, prompting me to add two a ...

Open Zurb Foundation Reveal Modal from the bottom of the screen

Struggling to make the reveal modal open from the bottom of the window. Any assistance would be highly appreciated. I've been attempting to tweak the open function with the reveal js, as seen in the original code below. Thank you, P open : function ...

Significant lag experienced when using $rootscope.$on with a large object

In my AngularJS project, I am working with a JavaScript object (factory) that contains numerous functions spanning 4000 lines. Creating the object from data fetched from PHP happens pretty quickly. $http.get('pivots/list.php') .succe ...

Real-time data update with Socket io: instantly refresh data on another page upon form submission without having to manually

What is the best way to utilize socket io in a situation where I have two pages open, one displaying a table of existing data and the other featuring a form for users to input new data? I want the table page to automatically update whenever a user submits ...

Unable to pass values to the controller using JQuery Load functionality

I am attempting to send a complicated object to the controller using ajax Load(), but I am encountering an issue where the object is null on the controller. I have come across similar inquiries, however, they pertain to codeIgniter whereas I am utilizing ...

The CSS specificity of a nested HTML element with no explicitly defined styles

Seeking clarification on this specific CSS cascading/inheritance rule. In the given example, I would have expected the text inside the em tag to be colored #000000, but I was informed that it would actually be colored #ff0000. I am familiar with CSS speci ...

The node.js system automatically restarts an API call when a timeout occurs

Current Setup: I am using a combination of sails.js for the backend API and React for the frontend. The communication between the frontend and backend is handled by the fetch API. Scenario: Within some of my API endpoints, I need to run an external file ...