Home > Blockchain >  Scroll page with keypress according to focused element
Scroll page with keypress according to focused element

Time:01-25

I am trying to achieve that on keypress, the page scrolls according to the focused div, at the moment, the keypress scrolls correctly through the divs but what I need to achieve is that the page scrolls with the focused item. At the moment it lags behind. The first few items are fine, but then the focused div goes lower than what is displayed on the page.

Here are the snippets of code that I am using:

This gets the keypress and works correctly on a page that does not need to scroll (less that a screens worth of content):

<script>
$('.focused').focus();
$(document).keydown(function(e){    
    if (e.keyCode == 38) { // left
        if($('.focused').prev('.focusable').length)
$('.focused').removeClass('focused').prev('.focusable').focus().addClass('focused');
    }
    if (e.keyCode == 40) { // right
        if($('.focused').next('.focusable').length)
$('.focused').removeClass('focused').next('.focusable').focus().addClass('focused');
    }
    if (e.keyCode == 8) { 
window.history.back();
    }
});
</script>

And these are the elements (the first one is set as focused the others are not, the keypress cycles through them).

<div >
    <a href="/items" >
        <div >
            <img src=items.jpg">
            <div >
                <h3>' . $content . '</h3>
            </div>
        </div>
    </a>
</div>

<div >
    <a href="/items" >
        <div >
            <img src=items.jpg">
            <div >
                <h3>' . $content . '</h3>
            </div>
        </div>
    </a>
</div>

There are a number (up to 20) of divs on each page.

I'm not sure how to make the page scroll down enough to to show focused div.

Any help would be appreciated. Thanks.

CodePudding user response:

You can use html!

Choose where you want to scroll. for example a div. Add an id to the div.

<div id="exampleId">

Use an a tag to scroll the div. In the tag href section, write the id of the div you want to wrap using #.

<a href="#exampleId">Scroll Me To The Example Div !</a>

yes now clicking this link will scroll you to the div with id exampleId. You can shape the optional a tag like a button.

CodePudding user response:

use like this

const scrolldown = () => {
const btn = document.querySelector("#sections");
btn.scrollBy({ left: 200, behavior: "smooth" });
}
  •  Tags:  
  • Related