JQuery – Scroll-Selecting Bootstrap Dropdown Value By KeyPressed

Scroll <ul> or <ol> list when a key is pressed. The list is scrolled where an element that starts with the key pressed exists in the list of <li> elements.

/**
 * Scroll to target element inside to other (parent) element
 * 
 * Example of use: $("#parent-id").scrollTo("#child-id");	 
 * The scroll-effect is visible if the "#parent-id" element is limited in size, the vertical-scroll bar appears and the "#child-id" is outside the visible area.
 * 
 * @param selector	elem	Target/Child element inside to other (parent) element
 */		
jQuery.fn.scrollTo = function(elem) { 							
  $(this).scrollTop($(this).scrollTop() - $(this).offset().top + $(elem).offset().top); 
  return this; 
};

/**
 * Scroll-Selecting Bootstrap Dropdown By KeyPressed Code/Char
 * 
 * The list must be sorted alphabetically for a usable result !
 *
 * @param selector	element   The <ul> element visible after a selection (dropdown-menu, dropdown-toggle)
 * @param int   	key	 Character pressed
 */	
function scrollToElementOnKeyPressed(element, key) {			
  key = String.fromCharCode( key ).toUpperCase(); 

  if ($(element).is(":visible")){ 
    $(element).find('li').each(function(){	
      let li0 = $(this).text().trim().charAt(0).toUpperCase();
      if (li0 == key) {
        $(element).scrollTo( $(this) );
        return false;
      }				
    });			
  }
}

/* --- Example of use: --- */

$(document).keypress(function( event ) {		
  scrollToElementOnKeyPressed('#CategoryList', event.which);
  scrollToElementOnKeyPressed('#MaterialeList', event.which);
});

If the text in the <li> element starts with the letter/key pressed, then the <ul> window  is scrolled to the first element found.

The list must be sorted alphabetically for a usable result !

Code and design example

QUERY – SCROLL-SELECTING BOOTSTRAP

Happy coding for all !

byrev Written by:

Be First to Comment

Leave a Reply

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