why page jumping up and down and focus move in javascript?

Viewed 19

I am trying to create custom select box.I am able to create select box or drop down. I am facing issue while using ArrowUp and ArrowDown key.

Expected Behaviour : When user press ArrowDown focus move to next element.

Current Output : focus move to next element , But page is jumping up and down look very bad.

here is my code

https://codesandbox.io/s/youthful-solomon-yd2t2t?file=/index.html

document.addEventListener("keydown", function(event) {
  if (event.key === "ArrowDown") {
    console.log("ArrowDown");
    let $elm = query(document, "li.ro-select-item-active");
    $elm.classList.remove("ro-select-item-active");
    if ($elm.nextElementSibling) {
      $elm.nextElementSibling.classList.add("ro-select-item-active");
      query(document, ".ro-select-item-active") ? .scrollIntoView({
        block: "center",
        inline: "nearest"
      });
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="ro-select" name="opts" placeholder="Select an option">
  <option value="1">First item</option>
  <option value="2">Second item</option>
  <option value="3">Third item</option>
  <option value="4">Last item</option>
  <option value="555">Last item</option>

  <option value="11">sssFirst item</option>
  <option value="22">ssc Second item</option>
  <option value="33">sdds Third item</option>
  <option value="44">Last item</option>
  <option value="5555">Last item</option>
</select>

Steps to reproduce bug

  1. Click on text field
  2. a pop up will open Highlight first element or highlight first li item.
  3. Press ArrowDown key move the focus to next element . but page will jump UP and down.
1 Answers

Easy to fix. Add event.preventDefault() to your code to prevent the keys from scrolling through the page. Learn more from MDN.

Add the code here:

if (event.key === "ArrowDown") {
   event.preventDefault(); // <--- !Add here!      
   console.log("ArrowDown");
   let $elm = query(document, "li.ro-select-item-active");
...

Make sure to also add this line when you're using "ArrowUp", etc...

Related