Text will scroll within a DIV when a key is pressed

Is there a way to implement a scroll effect on the div using the SPACE key? I would like the first span to move out of sight while the rest become visible when the key is pressed.

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 there's a CSS-only solution for this, I'd prefer that option.

Answer №1

Make sure to include
after each period.

/* Your Updated JavaScript */
<script language="javascript>

// Count the number of elements with the same class name.
var items = document.getElementsByClassName("item1").length;

i=0; // initialize a variable to track 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 move to the next <span>

}
});

</script>

This code should help you resolve your problem 😊

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing GraphicsMagick with Node.js to Extract Page Frames from Multi-Page TIF Files

I am currently working with a JavaScript script that can successfully convert a single page TIF file to JPEG. However, I am facing difficulties in determining whether "GraphicsMagick For Node" (https://github.com/aheckmann/gm) has the capability to extra ...

When using ReactDOM.render, make sure to provide a function as the last optional `callback` argument

I recently started learning React and I encountered the following error message after writing this code: ReactDOM.render Expected the last optional `callback` argument to be a function. `Instead received: Object` This is my code var Stats = Reac ...

The issue of Access-Control-Allow-Origin not functioning properly when using Ajax for a POST request

I am encountering an issue with the header "Access-control-allow-origin" when making a request using the following code: <script type='text/javascript'> function save() { $.ajax( { type: 'POST', ur ...

AnimationHandler does not animate the Three.js Mesh

I've been struggling to animate the exported mesh from my blender. Even the included buffalo mesh that I see animated in the example is not working for me. I've been attempting to replicate it without success. Here's the code, and I think th ...

Showing information in <select> depending on the selection of another <select>

I am working on a form that includes two drop down menus. My goal is to dynamically create an SQL query based on the option selected in the first drop down menu, retrieve relevant data from the database, and display it in the second drop down menu. Here i ...

How to Align Title in the Center of a Section Containing Multiple Images?

I have a situation where I am using a StyledHead section to display 10 images from an API. The images are wrapped in another section called StyledHeader, which also contains an h1 element. How can I center the h1 element both vertically and horizontally so ...

Creating HTML dynamic lists that remain fixed to the bottom of the viewport, regardless of any changes in their content

I want to create a dynamic list that displays like this - <div class="list-wrapper"> <ul class="list"> <li class="list-item"> ... </li> <li class="list-item"> ... </ ...

Creating new form fields dynamically using JavaScript (triggered by onClick event)

I want to dynamically add fields based on user interaction. For instance, when the checkbox or radio button is clicked, additional fields like buttons and textfields should appear. Is it possible to achieve this using onClick? If so, can you please provide ...

Error encountered while compiling ./node_modules/@material-ui/core/ButtonBase/ButtonBase.js

I've encountered a frustrating error message: Failed to compile ./node_modules/@material-ui/core/ButtonBase/ButtonBase.js Module not found: Can't resolve '@babel/runtime/helpers/builtin/assertThisInitialized' in 'E:\IT&bsol ...

The PHP table fails to show up on the screen

I've implemented a PHP script that connects to a MySQL database and is supposed to generate an HTML table. To achieve real-time updates, I've set up a long-polling AJAX script that polls the PHP script every second. Although everything seems to b ...

Breaking up the HTML elements assigned to a single controller can render the controller inoperable

When I create two divs controlled by the same controller in Angular, I notice that the controller stops updating my view. To illustrate this issue, I have prepared a simple example. You can view the sample here on JSFiddle, or you can also refer to the co ...

Tips for creating a custom axios response depending on the error code returned by the response

I am currently working on implementing a global error handling system in my Vue application. Within my project, I have an api.service.js file that contains the necessary code for Axios setup and various HTTP request functions such as get and post: /** * S ...

No wrapping of columns in Bootstrap 4

I am struggling with preventing the B4 columns from wrapping when resizing the Browser. Check out my code below: <div class="card card-outline-primary"> <div class="card-block"> <form class="row"> <div class="col-xs-4" sty ...

Tips for identifying truncated text when resizing the td element

While using the resize option in my table, I noticed that it cuts off some text. How can I determine the size at which the text begins to get cut off? https://i.sstatic.net/X7tKK.png This issue occurs when I resize the header https://i.sstatic.net/peycT. ...

Conceal the scrollbar while navigating within the parent container

I'm currently working on implementing a parallax header on my WordPress site using the Divi theme. Below is the code I have so far: <div class="parallax"> <div class="parralax__layer parallax__layer--back"> <img src="https://crisp ...

When a global variable is defined after a return statement within a function declaration, it does

Check out this Javascript code snippet: http://jsfiddle.net/ramchiranjeevi/63uML/ var foo = 1; function bar() { foo = 10; return; function foo() {} } bar(); console.log(foo); // should return 10, but returns 1 It's interesting to no ...

Issue with form not being validated

I'm attempting to disable the submit button when a user enters something in the email field, but despite validation, it is not working as expected. What could be the issue with my validation code? function validateEmail(email) { var btnSubmit = ...

AngularJS ng-repeat items do not properly align when utilizing Bootstrap col-md-2 styles

Utilizing AngularJS ng-repeat for displaying a list of products and incorporating bootstrap col-md-2 to showcase 6 products in each row, I have included a condensed version of my code below: <!DOCTYPE html> <html lang="en"> <head> <ti ...

How can I update jQuery CSS method on resize event?

Having trouble vertically centering a div inside the body? I've come up with a jQuery function that calculates the ideal margin-top value for achieving perfect vertical alignment. Here's how it works: Obtain container height, Get child height, ...

Utilizing Rollup to Bundle a Collection of React Components

I am diving into the world of bundling as I update a compact React component library internally powered by Rollup. Current Status Currently, all components are bundled into a single index.js file. When I import one or more... import { Button, Input } fr ...