-1

I want to create a scroll effect on the div such that when the SPACE key is pressed, the first span moves up out of visibility and the span become visible.

HTML

<div class="scroll-div">
  <span class="item1">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Rerum, beatae.</span>
  <span class="item1">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Rerum, beatae.</span>
  <span class="item1">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Rerum, beatae.</span>
  <span class="item1">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Rerum, beatae.</span>
</div>

CSS

.scroll-div{
  width: 150px;
  height: 100px;
  overflow-y: scroll;
}

JS

const scrollDiv = document.querySelector('.scroll-div');
scrollDiv.addEventListener('keydown', event => {
  if(event.key == ' '){
    ...scroll up;
  }
})

PS: If it can be done with CSS alone, I would prefer that.

humleAfriqan
  • 59
  • 10
  • can't be completely css, but with js check for span with scrolltop property that's inside scroll, on enter key event just fetch next element scrolltop property and use it for scroll. – MJN May 11 '20 at 18:07
  • Here the problem isn't so much with the event, as with element focus. If the div element has "focus" (e.g. if you've clicked on it, or tabbed to it if it has a tab stop assigned), it will do what you want, with no JavaScript, in most browsers. If you want it to respond to a space without being focused, you'd need a keydown listener on the window or body elements, not the div. – David784 May 11 '20 at 18:11

1 Answers1

0

You must use
at the end of each .

/* Your Modified Javascript */
<script language="javascript">

//Get the no of elements having the same classname.
var items = document.getElementsByClassName("item1").length;

i=0; //set a variable to get the current element.

const scrollDiv = document.querySelector('.scroll-div');
scrollDiv.addEventListener('keydown', event => {
if(event.key == ' '){

//Scroll to each element on every key press
document.getElementsByClassName("item1")[i].scrollIntoView({behavior: "smooth"});
i++;    //Increment the value of i to jump to next <span>

}
});

</script>

Hope this Code will Solve your issue