How to scroll a select list with JavaScript or jQuery?

I have a select tag:

           <select size="3"> 
           <option value="1">value 1</option> 
           <option value="2">value 2</option> 
           <option value="3">value 3</option> 
           <option value="4">value 4</option> 
           <option value="5">value 5</option> 
           <option value="6">value 6</option> 
           <select> 

Now it displays first 3 options, how can I scroll to see elements from 3-5 or 4-6 using jQuery or pure JavaScript?

Answers:

Answer

.scrollTop() may work:

$('select').scrollTop(30);

And you can scroll to a particular element using this:

var $s = $('select');

var optionTop = $s.find('[value="3"]').offset().top;
var selectTop = $s.offset().top;

$s.scrollTop($s.scrollTop() + (optionTop - selectTop));

Try it here: http://jsfiddle.net/kj9p4/

Note: does not work in Chrome.

Answer
 $("select").scrollTop($("select").find("option[value=4]").offset().top);

Just set the appropriate selectors for select element and values inside

Answer

I built this extension which is a more appropriated solution to this problem. It's flexible and reusable and it's built on top of jQuery. http://jsfiddle.net/db86eu91/4/

;(function(){
/**
The MIT License (MIT)

Copyright (c) 2015 Márcio Reis [email protected]

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
$.fn.ScrollToValue = function(target){
    var $select = $(this);
    if (!$select.length) return;

    var value = target;

    //how many pixels is the select list scrolled from the moment we run this code???
    var distanceScrolledFromTop = $select.scrollTop();
    //how many pixels separate the top of the page from the <select> element that we pretend to manipulate
    var offsetSelect = $select.offset().top;
    //assuming a offset().top of 0 on our list how many pixels separate our target option from the top of the page? 
    var offsetElement = $select.find('[value=' + value + ']').offset().top + distanceScrolledFromTop;

    //Because the offset of our element is always bigger than the offset of our select box, we must subtract the offset of our target element by the offset of our list. That's it
    $select.scrollTop(offsetElement - offsetSelect);
}

})();
Answer

This is coffescript using jquery, (coffeescript translates directly into javascript)

exports.mylist_scroll_to  = (value) ->
    element = $("#mylist")[0]
    item_height = element.scrollHeight/element.length
    $("#mylist").scrollTop(item_height*(element.selectedIndex))
Answer

Or you can just use focus().

$("select").find("option[value=4]").focus();
$('select option[value="banana"]').focus();
Answer

You can use the val() function on your list. Use last item from the ones you want to display as the argument

$("#foo").val('5');

This will show 3-5.

Answer

Here is a workaround to this

Working demo

Code

$(function(){
    //Select the last option in the range which you want to scroll to
    var lastOption = $("select").find("option[value=5]")
        //Store the selection state
        var isSelected = lastOption.is(":selected");

        lastOption.attr("selected", true)//This will scroll to the option
            .attr("selected", isSelected); //Restore the selection state
});
Answer

Although its from 2011, I was facing a large problem with Primefaces, as I use listboxes extensively.

When I load items from a database in order to populate many listboxes, they werent scrolled by default.

I fixed this by creating a JavaScript function.

//This function is used in primefaces listboxes with many items (which doesnt use the HTML tag 'option value="XXX" selected'). So, by default, if the current selected item is out of view, like near the bottom end, the scroll doesnt execute at all.

In order to use the function below, you need to put a javascript call in your listbox, like oncomplete="autoScrollListBox('#form\:lixtboxID');"

You can customize this function to traverse/loop through other lists, like dataTables or customized ui-******-***** names (just change them below).

function autoScrollListBox(id) {
    var listContainer=id+'  .ui-selectlistbox-listcontainer';
    var listContainerList=id+'  .ui-selectlistbox-listcontainer  .ui-selectlistbox-list';

    var listTop = $(listContainerList).offset().top;
    var selectedContainer=id+ ' .ui-state-highlight';
    var selectedOptionTop =$(id+' .ui-state-highlight').offset().top;
   $(listContainer).animate( {scrollTop:selectedOptionTop-listTop});
    }

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.