I was trying to call different functions using JavaScript when a key is pressed. It worked perfectly! How can I achieve the same effect by using the scroll wheel?
The goal is to change the background image of the webpage, carry out a query in a SQL Table and store the x and y co ordinates of the pointer in a table.
Hope this can help :)
$(document).scroll(()=>{
if($(document).scrollTop() >= 970){
//If you want to get style permenent remove line below
$("body").css("background","red");
}
else if($(document).scrollTop() >= 508){
//If you want to get style permenent remove line below
$("body").css("background","blue");
}
else if($(document).scrollTop() >= 8){
//If you want to get style permenent remove line below
$("body").css("background","indigo");
}
})
/*This is for smooth scrolling*/
html {
scroll-behavior: smooth;
}
.big {
height: 500px;
width: 100%;
border: solid black 1px;
}
.active {
color:red;
}
<div id="main">
<div class="big" id ="home">Home</div>
<div class="big" id ="about">About Us</div>
<div class="big" id ="contacts">Contacts</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
You're looking at the onscroll and scroll event.
<div onscroll="myFunction()"></div>
or
document.getElementById("myDIV").addEventListener("scroll", myFunction);
or
document.getElementById("myDIV").onscroll = function() {myFunction()};
and add the function in all cases:
function myFunction() {
console.log("It works");
}
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onscroll
https://www.w3schools.com/jsref/event_onscroll.asp
I am trying to make an element #mask123 visible or hidden upon click. By default, the element is hidden, but as I click it becomes visible. The js below works on first click, and the element turns visible. Now, I would like to click on the same button #menu-btn-toggle and the element toggles into invisible mode, which I cannot make it work. I am using inline css here. This is a simple case but my limited knowledge on js is not helping me.
<div id="menu-btn">
<a href="#" title="Menu" id="menu-btn-toggle" class="menu-icon-link" onclick="showMask();">
</div>
the html code
<div class="side-nav--mask">
<div class="js-side-nav-mask liquid-container">
<div id="mask123" class="liquid-child" style="visibility: hidden; top: 0px; left: 0px; opacity: 1;"></div>
</div>
</div>
Here is my JS:
<script type="text/javascript">
function showMask() {
var node = document.getElementById('mask123')
node.style.visibility = 'visible';
}
</script>
When I try to a condition (below) it does not work:
<script type="text/javascript">
function showMask() {
var node = document.getElementById('mask123')
node.style.visibility = 'visible';
if node.is(":visible") {
node.style.visibility = 'hidden';
}
}
</script>
function showMask() {
var node = document.getElementById('mask123');
if (node.style.visibility=='visible') {
node.style.visibility = 'hidden';
}
else
node.style.visibility = 'visible'
}
This is how you should use your if condition :)
Try to toggle the visibility property based on current value of it,
function showMask() {
var node = document.getElementById('mask123')
var visibility = node.style.visibility;
node.style.visibility = visibility == "visible" ? 'hidden' : "visible"
}
You are accessing the jquery's is() function over a plain node object. Node object doesn't have function called is in its prototype.
.is is a jquery method. To use it, you first need to wrap your element/selector with jquery - $('#mask123').is(':visible').
But you don't actually need jquery for this, you can do it in basic JS:
function showMask() {
var node = document.getElementById('mask123')
if (node.style.visibility === 'visible') {
node.style.visibility = 'hidden';
} else {
node.style.visibility = 'visible';
}
}
If you don't mind using jQuery you can use a simple function and a CSS class:
// after removing onclick="" attribute from html
$('#menu-btn-toggle').click(function(){
$('#mask123').toggleClass('visible');
});
#mark123.visible{
visibility: visible;
}
Note that in this case you also have to specify that #mask123 is initially hidden in order to do the transition to visible.
So you have to add this to your CSS
#mask123 {
visibility:hidden; /* initial state = hidden */
}
-
Working jsFiddle
Use ClassList.toggle and since you are using inline code you will need important
var btn = document.querySelector("#menu-btn-toggle"),
mask123 = document.querySelector("#mask123");
function classToggle() {
mask123.classList.toggle("visible")
}
btn.addEventListener("click", classToggle, false)
#mask123.visible{
visibility: visible!important;
}
<div id="menu-btn">
Click to toggle
</div>
<div class="side-nav--mask">
<div class="js-side-nav-mask liquid-container">
<div id="mask123" class="liquid-child" style="visibility: hidden; top: 0px; left: 0px; opacity: 1;">Some text</div>
</div>
</div>
i have the following code, and I am trying to figure out how can I set the first button to white if I click it once again, same thing for the next button.
So,if i clicked it once it turns red, but if I click again, it turns white.
any ideas.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> color divs </title>
<meta name="author" content="Lee Middleton" />
<meta name="keywords" content="CIS120/121/122" />
<meta name="description" content="Template for x/html, CSS and JavaScript" />
<style type="text/css">
.container {
border: 1px solid blue;
border-radius: 10px;
width: 100px;
height: 50px;
}
</style>
<script language="javascript">
function changeColor(whichOne)
{
var thatOne = eval(whichOne);
var element = document.getElementById(whichOne);
var color = "ff";
var stringColor;
if (whichOne == 1)
{
stringColor = "#" + color + "0000";
else {
alert('it was clicked') ;
}
}
}
else if (whichOne== 2)
{
stringColor = "#0000" + color;
}
element.style.backgroundColor = stringColor;
}
</script>
<body>
<div class='container' id='1' style='margin: 150px 0 0 75px; float: left;' onclick='changeColor(1);'></div>
<div class='container' id='2' style='margin: 150px 0 0 175px; float: left;' onclick='changeColor(2);'></div>
<div class='container' id='3' style='margin: 150px 0 0 220px; float: left;' onclick='changeColor(3);'></div>
</body>
</html>
As the other solution mentions you could store the previous color in a variable so you can reset it when necessary, but there is an easier way if you just want to return the element to its default colour.
Just do:
element.style.backgroundColor = '';
This just unsets the background-color part of the style attribute, allowing for the color from the css to be used.
So to toggle between default and a colour you can just do this:
element.style.backgroundColor = element.style.backgroundColor ? '' : '#' + color;
You need to save the previous state of the button outside this function like that
var prevColor = "#ffffff";
function changeColor(whichOne) {
prevColour = (this.prevColor=="#ffffff")?"#ff0000":"#ffffff";
// use this prevColour to change button colour
}
1st point
You got some {} closure problem.
Your first if contains an else without an if associated with it.
This same if is close {} but you close it again before the else if
2nd
If I understand right you are having a function to toggle the color of the button base on it's ID.
I would write something similar to this
if(document.getElementById(whichOne).style.backgroundColor==COLOR1)
{
document.getElementById(whichOne).style.backgroundColor = COLOR2
}
else
documenet.getElementById(whichOne).style.backgroundColor = COLOR2
Color 1 and Color 2 and constants in the function, no need to fill the namespace.
Toggle the background-color or which ever attributes you want to manipulate via CSS markup from a toggle event.
Add this class to your CSS
.container {
background-color: #d1d1d1;
}
.colorMe{
background-color: red;
}
Use this script
$(document).ready(function(){
$('.container').on("click", function(){
$(this).toggleClass('colorMe');
});
});
HTML
<div class='container'> Button-1 </div>
<div class='container'> Button-2 </div>
<div class='container'> Button-3 </div>
Dont forget to link a jQuery library.
Here is a live working example: JsFiddle Example
If all you want to do is change the appearance then you should stick to CSS classes. It is this type of inline code that can give you a headache when you go to debug it months down the road when the client wants it to turn pink instead of white.
Likewise on the inline event binding. Javascript can be invoked several ways and it can quickly become a burden keeping track of them all when there are little snippets scattered throughout your HTML.
I recommend something like the following:
HTML
<div class='container green' id='1' ></div>
<div class='container blue' id='2' ></div>
<div class='container yellow' id='3'></div>
STYLES
.container.active { background-color:white;}
JAVASCRIPT
function changeColor(el){
var classes = el.className.split(' '), // get the current classes
index = classes.indexOf('active'), // see if 'active' is one of them
hasClass = index > -1;
if (hasClass)
el.className = (classes.splice(index, 1), classes.join(' ')); // remove 'active' and stringify
else
el.className+= " active";
}
// put all calls that require the DOM to be loaded in a function
function init(){
var divs = document.getElementsByClassName('container'), // get all elements that need binding
divCount = divs.length; // the length of the array for looping
// loop through array
while(divCount--){
// bind each element
// using an anonymous function wrapper to pass 'this' parameter
divs[divCount].addEventListener('click', function() { changeColor(this) });
}
}
// fire the init function once the window is loaded
window.addEventListener('load', init);
http://jsfiddle.net/NpW9X/
You could try this:
JavaScript:
var times = 0;
function isEven(num) {
if (num % 2 == 0) return true;
else return false;
}
function changeColor(whichOne) {
if (isEven(times)) {
document.getElementById(whichOne).style.color = 'white';
} else {
document.getElementById(whichOne).style.color = 'red';
}
times++;
}
I have a scrolled div and I want to have an event when I click on it, it will force this div to scroll to view an element inside.
I wrote its JavasSript like this:
document.getElementById(chr).scrollIntoView(true);
but this scrolls all the page while scrolling the div itself.
How to fix that?
I want to say it like this:
MyContainerDiv.getElementById(chr).scrollIntoView(true);
You need to get the top offset of the element you'd like to scroll into view, relative to its parent (the scrolling div container):
var myElement = document.getElementById('element_within_div');
var topPos = myElement.offsetTop;
The variable topPos is now set to the distance between the top of the scrolling div and the element you wish to have visible (in pixels).
Now we tell the div to scroll to that position using scrollTop:
document.getElementById('scrolling_div').scrollTop = topPos;
If you're using the prototype JS framework, you'd do the same thing like this:
var posArray = $('element_within_div').positionedOffset();
$('scrolling_div').scrollTop = posArray[1];
Again, this will scroll the div so that the element you wish to see is exactly at the top (or if that's not possible, scrolled as far down as it can so it's visible).
You would have to find the position of the element in the DIV you want to scroll to, and set the scrollTop property.
divElem.scrollTop = 0;
Update:
Sample code to move up or down
function move_up() {
document.getElementById('divElem').scrollTop += 10;
}
function move_down() {
document.getElementById('divElem').scrollTop -= 10;
}
Method 1 - Smooth scrolling to an element inside an element
var box = document.querySelector('.box'),
targetElm = document.querySelector('.boxChild'); // <-- Scroll to here within ".box"
document.querySelector('button').addEventListener('click', function(){
scrollToElm( box, targetElm , 600 );
});
/////////////
function scrollToElm(container, elm, duration){
var pos = getRelativePos(elm);
scrollTo( container, pos.top , 2); // duration in seconds
}
function getRelativePos(elm){
var pPos = elm.parentNode.getBoundingClientRect(), // parent pos
cPos = elm.getBoundingClientRect(), // target pos
pos = {};
pos.top = cPos.top - pPos.top + elm.parentNode.scrollTop,
pos.right = cPos.right - pPos.right,
pos.bottom = cPos.bottom - pPos.bottom,
pos.left = cPos.left - pPos.left;
return pos;
}
function scrollTo(element, to, duration, onDone) {
var start = element.scrollTop,
change = to - start,
startTime = performance.now(),
val, now, elapsed, t;
function animateScroll(){
now = performance.now();
elapsed = (now - startTime)/1000;
t = (elapsed/duration);
element.scrollTop = start + change * easeInOutQuad(t);
if( t < 1 )
window.requestAnimationFrame(animateScroll);
else
onDone && onDone();
};
animateScroll();
}
function easeInOutQuad(t){ return t<.5 ? 2*t*t : -1+(4-2*t)*t };
.box{ width:80%; border:2px dashed; height:180px; overflow:auto; }
.boxChild{
margin:600px 0 300px;
width: 40px;
height:40px;
background:green;
}
<button>Scroll to element</button>
<div class='box'>
<div class='boxChild'></div>
</div>
Method 2 - Using Element.scrollIntoView:
Note that browser support isn't great for this one
var targetElm = document.querySelector('.boxChild'), // reference to scroll target
button = document.querySelector('button'); // button that triggers the scroll
// bind "click" event to a button
button.addEventListener('click', function(){
targetElm.scrollIntoView()
})
.box {
width: 80%;
border: 2px dashed;
height: 180px;
overflow: auto;
scroll-behavior: smooth; /* <-- for smooth scroll */
}
.boxChild {
margin: 600px 0 300px;
width: 40px;
height: 40px;
background: green;
}
<button>Scroll to element</button>
<div class='box'>
<div class='boxChild'></div>
</div>
Method 3 - Using CSS scroll-behavior:
.box {
width: 80%;
border: 2px dashed;
height: 180px;
overflow-y: scroll;
scroll-behavior: smooth; /* <--- */
}
#boxChild {
margin: 600px 0 300px;
width: 40px;
height: 40px;
background: green;
}
<a href='#boxChild'>Scroll to element</a>
<div class='box'>
<div id='boxChild'></div>
</div>
Native JS, Cross Browser, Smooth Scroll (Update 2020)
Setting ScrollTop does give the desired result but the scroll is very abrupt. Using jquery to have smooth scroll was not an option. So here's a native way to get the job done that supports all major browsers. Reference - caniuse
// get the "Div" inside which you wish to scroll (i.e. the container element)
const El = document.getElementById('xyz');
// Lets say you wish to scroll by 100px,
El.scrollTo({top: 100, behavior: 'smooth'});
// If you wish to scroll until the end of the container
El.scrollTo({top: El.scrollHeight, behavior: 'smooth'});
That's it!
And here's a working snippet for the doubtful -
document.getElementById('btn').addEventListener('click', e => {
e.preventDefault();
// smooth scroll
document.getElementById('container').scrollTo({top: 175, behavior: 'smooth'});
});
/* just some styling for you to ignore */
.scrollContainer {
overflow-y: auto;
max-height: 100px;
position: relative;
border: 1px solid red;
width: 120px;
}
body {
padding: 10px;
}
.box {
margin: 5px;
background-color: yellow;
height: 25px;
display: flex;
align-items: center;
justify-content: center;
}
#goose {
background-color: lime;
}
<!-- Dummy html to be ignored -->
<div id="container" class="scrollContainer">
<div class="box">duck</div>
<div class="box">duck</div>
<div class="box">duck</div>
<div class="box">duck</div>
<div class="box">duck</div>
<div class="box">duck</div>
<div class="box">duck</div>
<div class="box">duck</div>
<div id="goose" class="box">goose</div>
<div class="box">duck</div>
<div class="box">duck</div>
<div class="box">duck</div>
<div class="box">duck</div>
</div>
<button id="btn">goose</button>
Update: As you can perceive in the comments, it seems that Element.scrollTo() is not supported in IE11. So if you don't care about IE11 (you really shouldn't, Microsoft is retiring IE11 in June 2022), feel free to use this in all your projects. Note that support exists for Edge! So you're not really leaving your Edge/Windows users behind ;)
Reference
To scroll an element into view of a div, only if needed, you can use this scrollIfNeeded function:
function scrollIfNeeded(element, container) {
if (element.offsetTop < container.scrollTop) {
container.scrollTop = element.offsetTop;
} else {
const offsetBottom = element.offsetTop + element.offsetHeight;
const scrollBottom = container.scrollTop + container.offsetHeight;
if (offsetBottom > scrollBottom) {
container.scrollTop = offsetBottom - container.offsetHeight;
}
}
}
document.getElementById('btn').addEventListener('click', ev => {
ev.preventDefault();
scrollIfNeeded(document.getElementById('goose'), document.getElementById('container'));
});
.scrollContainer {
overflow-y: auto;
max-height: 100px;
position: relative;
border: 1px solid red;
width: 120px;
}
body {
padding: 10px;
}
.box {
margin: 5px;
background-color: yellow;
height: 25px;
display: flex;
align-items: center;
justify-content: center;
}
#goose {
background-color: lime;
}
<div id="container" class="scrollContainer">
<div class="box">duck</div>
<div class="box">duck</div>
<div class="box">duck</div>
<div class="box">duck</div>
<div class="box">duck</div>
<div class="box">duck</div>
<div class="box">duck</div>
<div class="box">duck</div>
<div id="goose" class="box">goose</div>
<div class="box">duck</div>
<div class="box">duck</div>
<div class="box">duck</div>
<div class="box">duck</div>
</div>
<button id="btn">scroll to goose</button>
Code should be:
var divElem = document.getElementById('scrolling_div');
var chElem = document.getElementById('element_within_div');
var topPos = divElem.offsetTop;
divElem.scrollTop = topPos - chElem.offsetTop;
You want to scroll the difference between child top position and div's top position.
Get access to child elements using:
var divElem = document.getElementById('scrolling_div');
var numChildren = divElem.childNodes.length;
and so on....
If you are using jQuery, you could scroll with an animation using the following:
$(MyContainerDiv).animate({scrollTop: $(MyContainerDiv).scrollTop() + ($('element_within_div').offset().top - $(MyContainerDiv).offset().top)});
The animation is optional: you could also take the scrollTop value calculated above and put it directly in the container's scrollTop property.
We can resolve this problem without using JQuery and other libs.
I wrote following code for this purpose:
You have similar structure ->
<div class="parent">
<div class="child-one">
</div>
<div class="child-two">
</div>
</div>
JS:
scrollToElement() {
var parentElement = document.querySelector('.parent');
var childElement = document.querySelector('.child-two');
parentElement.scrollTop = childElement.offsetTop - parentElement.offsetTop;
}
We can easily rewrite this method for passing parent and child as an arguments
Another example of using jQuery and animate.
var container = $('#container');
var element = $('#element');
container.animate({
scrollTop: container.scrollTop = container.scrollTop() + element.offset().top - container.offset().top
}, {
duration: 1000,
specialEasing: {
width: 'linear',
height: 'easeOutBounce'
},
complete: function (e) {
console.log("animation completed");
}
});
None of other answer fixed my issue.
I played around with scrollIntoView arguments and managed to found a solution. Setting inline to start and block to nearest prevents parent element (or entire page) to scroll:
document.getElementById(chr).scrollIntoView({
behavior: 'smooth',
block: 'nearest',
inline: 'start'
});
There are two facts :
1) Component scrollIntoView is not supported by safari.
2) JS framework jQuery can do the job like this:
parent = 'some parent div has css position==="fixed"' || 'html, body';
$(parent).animate({scrollTop: $(child).offset().top}, duration)
Here's a simple pure JavaScript solution that works for a target Number (value for scrollTop), target DOM element, or some special String cases:
/**
* target - target to scroll to (DOM element, scrollTop Number, 'top', or 'bottom'
* containerEl - DOM element for the container with scrollbars
*/
var scrollToTarget = function(target, containerEl) {
// Moved up here for readability:
var isElement = target && target.nodeType === 1,
isNumber = Object.prototype.toString.call(target) === '[object Number]';
if (isElement) {
containerEl.scrollTop = target.offsetTop;
} else if (isNumber) {
containerEl.scrollTop = target;
} else if (target === 'bottom') {
containerEl.scrollTop = containerEl.scrollHeight - containerEl.offsetHeight;
} else if (target === 'top') {
containerEl.scrollTop = 0;
}
};
And here are some examples of usage:
// Scroll to the top
var scrollableDiv = document.getElementById('scrollable_div');
scrollToTarget('top', scrollableDiv);
or
// Scroll to 200px from the top
var scrollableDiv = document.getElementById('scrollable_div');
scrollToTarget(200, scrollableDiv);
or
// Scroll to targetElement
var scrollableDiv = document.getElementById('scrollable_div');
var targetElement= document.getElementById('target_element');
scrollToTarget(targetElement, scrollableDiv);
given you have a div element you need to scroll inside, try this piece of code
document.querySelector('div').scroll(x,y)
this works with me inside a div with a scroll, this should work with you in case you pointed the mouse over this element and then tried to scroll down or up. If it manually works, it should work too
User Animated Scrolling
Here's an example of how to programmatically scroll a <div> horizontally, without JQuery. To scroll vertically, you would replace JavaScript's writes to scrollLeft with scrollTop, instead.
JSFiddle
https://jsfiddle.net/fNPvf/38536/
HTML
<!-- Left Button. -->
<div style="float:left;">
<!-- (1) Whilst it's pressed, increment the scroll. When we release, clear the timer to stop recursive scroll calls. -->
<input type="button" value="«" style="height: 100px;" onmousedown="scroll('scroller',3, 10);" onmouseup="clearTimeout(TIMER_SCROLL);"/>
</div>
<!-- Contents to scroll. -->
<div id="scroller" style="float: left; width: 100px; height: 100px; overflow: hidden;">
<!-- <3 -->
<img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png?v=9c558ec15d8a" alt="image large" style="height: 100px" />
</div>
<!-- Right Button. -->
<div style="float:left;">
<!-- As (1). (Use a negative value of 'd' to decrease the scroll.) -->
<input type="button" value="»" style="height: 100px;" onmousedown="scroll('scroller',-3, 10);" onmouseup="clearTimeout(TIMER_SCROLL);"/>
</div>
JavaScript
// Declare the Shared Timer.
var TIMER_SCROLL;
/**
Scroll function.
#param id Unique id of element to scroll.
#param d Amount of pixels to scroll per sleep.
#param del Size of the sleep (ms).*/
function scroll(id, d, del){
// Scroll the element.
document.getElementById(id).scrollLeft += d;
// Perform a delay before recursing this function again.
TIMER_SCROLL = setTimeout("scroll('"+id+"',"+d+", "+del+");", del);
}
Credit to Dux.
Auto Animated Scrolling
In addition, here are functions for scrolling a <div> fully to the left and right. The only thing we change here is we make a check to see if the full extension of the scroll has been utilised before making a recursive call to scroll again.
JSFiddle
https://jsfiddle.net/0nLc2fhh/1/
HTML
<!-- Left Button. -->
<div style="float:left;">
<!-- (1) Whilst it's pressed, increment the scroll. When we release, clear the timer to stop recursive scroll calls. -->
<input type="button" value="«" style="height: 100px;" onclick="scrollFullyLeft('scroller',3, 10);"/>
</div>
<!-- Contents to scroll. -->
<div id="scroller" style="float: left; width: 100px; height: 100px; overflow: hidden;">
<!-- <3 -->
<img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png?v=9c558ec15d8a" alt="image large" style="height: 100px" />
</div>
<!-- Right Button. -->
<div style="float:left;">
<!-- As (1). (Use a negative value of 'd' to decrease the scroll.) -->
<input type="button" value="»" style="height: 100px;" onclick="scrollFullyRight('scroller',3, 10);"/>
</div>
JavaScript
// Declare the Shared Timer.
var TIMER_SCROLL;
/**
Scroll fully left function; completely scrolls a <div> to the left, as far as it will go.
#param id Unique id of element to scroll.
#param d Amount of pixels to scroll per sleep.
#param del Size of the sleep (ms).*/
function scrollFullyLeft(id, d, del){
// Fetch the element.
var el = document.getElementById(id);
// Scroll the element.
el.scrollLeft += d;
// Have we not finished scrolling yet?
if(el.scrollLeft < (el.scrollWidth - el.clientWidth)) {
TIMER_SCROLL = setTimeout("scrollFullyLeft('"+id+"',"+d+", "+del+");", del);
}
}
/**
Scroll fully right function; completely scrolls a <div> to the right, as far as it will go.
#param id Unique id of element to scroll.
#param d Amount of pixels to scroll per sleep.
#param del Size of the sleep (ms).*/
function scrollFullyRight(id, d, del){
// Fetch the element.
var el = document.getElementById(id);
// Scroll the element.
el.scrollLeft -= d;
// Have we not finished scrolling yet?
if(el.scrollLeft > 0) {
TIMER_SCROLL = setTimeout("scrollFullyRight('"+id+"',"+d+", "+del+");", del);
}
}
This is what has finally served me
/** Set parent scroll to show element
* #param element {object} The HTML object to show
* #param parent {object} The HTML object where the element is shown */
var scrollToView = function(element, parent) {
//Algorithm: Accumulate the height of the previous elements and add half the height of the parent
var offsetAccumulator = 0;
parent = $(parent);
parent.children().each(function() {
if(this == element) {
return false; //brake each loop
}
offsetAccumulator += $(this).innerHeight();
});
parent.scrollTop(offsetAccumulator - parent.innerHeight()/2);
}
I needed to scroll a dynamically loading element on a page so my solution was a little more involved.
This will work on static elements that are not lazy loading data and data being dynamically loaded.
const smoothScrollElement = async (selector: string, scrollBy = 12, prevCurrPos = 0) => {
const wait = (timeout: number) => new Promise(resolve => setTimeout(resolve, timeout));
const el = document.querySelector(selector) as HTMLElement;
let positionToScrollTo = el.scrollHeight;
let currentPosition = Math.floor(el.scrollTop) || 0;
let pageYOffset = (el.clientHeight + currentPosition);
if (positionToScrollTo == pageYOffset) {
await wait(1000);
}
if ((prevCurrPos > 0 && currentPosition <= prevCurrPos) !== true) {
setTimeout(async () => {
el.scrollBy(0, scrollBy);
await smoothScrollElement(selector, scrollBy, currentPosition);
}, scrollBy);
}
};
browser does scrolling automatically to an element that gets focus, so what you can also do it to wrap the element that you need to be scrolled to into <a>...</a> and then when you need scroll just set the focus on that a