Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript- find text within a page and jump to location in page

I have a webpage with a large list of records (say 250+ rows of data in a table) and want to be able to just visit the page, immediately start typing, and have it jump me to the first row that matches the text I have typed.

Ideally, if I then continued to type more characters so the first match doesn't match anymore, it could then continue to respond to my input and jump me to the new match.

I've tried with window.find() but haven't had much success... can anyone reccomend a working solution?

I'm essentially looking for the equivalent to hitting 'CTRL-F' on my keyboard... except without the need to hit CTRL-F to make it happen.

like image 837
Keith Palmer Jr. Avatar asked Dec 01 '10 17:12

Keith Palmer Jr.


People also ask

How do you jump to a specific section in JavaScript?

One can use the anchor tag to redirect to a particular section on the same page. You need to add ” id attribute” to the section you want to show and use the same id in href attribute with “#” in the anchor tag.

How do I go back to the same page in JavaScript?

The history.back() method loads the previous URL (page) in the history list. The history.back() method only works if a previous page exists.


1 Answers

I think the tricky part of this is actually the accepting of user input intelligently. Therefore, I'd say the best thing to do is to pass off your searching to an autocomplete-type plugin. Once the page is ready, you pass the focus to an input text box, and then let the plugin do its magic as you search...

For example, you could use the quicksearch plugin.

Then given a table of data and an input like this:

<input id="searcher" type="text" name="searcher">

You could have a ready function that looks like this:

$('#searcher').quicksearch('table tbody tr', {
    'delay': 100,
    'bind': 'keyup keydown',
    'show': function() {
        if ($('#searcher').val() === '') {
            return;
        }
        $(this).addClass('show');
    },
    'onAfter': function() {
        if ($('#searcher').val() === '') {
            return;
        }
        if ($('.show:first').length > 0){
            $('html,body').scrollTop($('.show:first').offset().top);
        }
    },
    'hide': function() {
        $(this).removeClass('show');
    },
    'prepareQuery': function(val) {
        return new RegExp(val, "i");
    },
    'testQuery': function(query, txt, _row) {
        return query.test(txt);
    }
});

$('#searcher').focus();

Try it out here: http://jsfiddle.net/ZLhAd/369/

EDIT: other answer/comment added in to make the input fixed and stop the scollbar jumping around so ridiculously.

like image 94
Ryley Avatar answered Oct 21 '22 07:10

Ryley