How to Scroll Down Selected Option into Visible View? – JavaScript

The solution is relatively simple, all you have to do is know the ID of the selection element!

1. If you want the action to be done automatically when a page loads

<script>
document.addEventListener("DOMContentLoaded", function(event) {
  var func_list = document.getElementById("func-list");
  var selected_func = func_list.options[func_list.selectedIndex];
  selected_func.scrollIntoView({behavior: "smooth", block: "center", inline: "nearest"});
});
</script>

2. If you want the scroll action to be performed following an event, for example when you press a button, jQuery example:

$('#button-id').click(function() {	   
   var func_list = document.getElementById("func-list");
   func_list.options[func_list.selectedIndex].scrollIntoView({behavior: "smooth", block: "center", inline: "nearest"});	   
});

 

 

byrev Written by:

Be First to Comment

    Leave a Reply

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