There are so many questions like my one,even I go through this link also.But I didnt get a proper solution yet.So Im posting my issue here.
I have to popup a message when click an icon and when I click the same div where the icon is reside,it should disappear. This is working fine.But when I click outside the div also, the popup should disappear.How can I modify this javascript function to achieve it
<div>
<h5 class="haead">Search for a product title
<div class="popup" onclick="myFunction5()"> <img class="qnicon" src="question.png">
<span class="popuptext" id="myPopup5">Search product.</span>
</div>
</h5>
</div>
<script>
function myFunction5() {
var popup = document.getElementById("myPopup5");
popup.classList.toggle("show");
}
</script>
The easiest way I've found that avoids any number of other problems you could encounter, is to put the popup on top of a 100% width/height div. That "disabler" div has the same click handler as the button that would ordinarily close the popup. So if the user clicks the "X" to close, the "Ok" button (or whatever you've got set up) or the area outside the popup, same effect, it closes.
That "disabler" div (it effectively disables the entire app except for the popup) can be completely clear, or translucent, by setting the opacity.
You put the "disabler" div at z = 9998, the popup at z = 9999 (just more CSS), and they'll always be on top. Note that this may not be necessary if all your content loads into a div that is already underneath the disabler (e.g. the router-outlet div in Angular), but I usually do it anyway.
Complete basic example. I typically make a component out of this and hook it into an event bus so I can pass data in and out of it (so I can change the position, style, messages, even what happens when you click the close button). If you get this code you should be able to use some approximation of it in any framework, etc.
<html>
<head>
<style>
.button {
text-align: center;
width: 100px;
height: 30px;
background-color: green;
border: 2px solid grey;
color: white;
margin: auto;
position: relative;
}
.disabler {
position: fixed;
top: 0px;
left: 0px;
width: 100%;
height: 100%;
z-index: 99998;
background-color: #000000;
opacity: 0.5;
}
.popup {
position: relative;
/* Center with whatever voodoo you like */
top: calc(50% - 150px);
left: calc(50% - 150px);
width: 300px;
height: 300px;
background-color: blue;
border: 2px solid grey;
z-index: 99999;
}
</style>
</head>
<body>
<div class="button" onclick="togglePopup ( )">
Show Popup
</div>
<div class="button" onclick="showAlert ( )">
Show Alert
</div>
<!-- This div is on top of everything except the popup div -->
<!-- It effectively disables the entire app except for the popup -->
<div id="disabler" class="disabler" onclick="togglePopup ( )"></div>
<!-- This div holds the popup -->
<!-- You can only close the popup by clicking the close button, or the disabler background -->
<!-- Clicking in the blue popup area doesn't do anything (intentionally) -->
<!-- Even though you can see other widgets through the disabler, they're all inaccessible -->
<!-- Try the show alert button to confirm -->
<div id="popup" class="popup">
<div class="button" onclick="togglePopup ( )">
Close Popup
</div>
</div>
<script type="text/javascript">
togglePopup ( ); // Hide them to start.
function togglePopup ( ) {
let disabler = document.getElementById ( 'disabler' );
disabler.style.display = disabler.style.display ? '' : 'none';
let popup = document.getElementById ( 'popup' );
popup.style.display = popup.style.display ? '' : 'none';
}
function showAlert ( ) {
alert ( 'Hey there!' );
}
</script>
</body>
</html>
Here is the way to do this:
Javascript
popup.addEventListener('click',function(e) {
// This is important to prevent the popup from inheriting the event since it
// is inside the body
e.stopPropagation();
});
var body = document.body;
body.addEventListener('click', function(e){
if(popup.classList.contains('show')) {
popup.classList.remove("show");
}
);
I wish this solves your problem
Edit
That didn't work because you have to structure your code properly like this:
HTML
<div id='popup-container'>
<!-- This all inside the popup -->
<h5 class="haead">Search for a product title</h5>
<div class="popup-data">
<img class="qnicon" src="question.png">
<span class="popuptext" id="myPopup5">Search product.</span>
</div>
Show Popup
</div>
Javascript
var popupContainer = document.getElementById('popup-container');
var body = document.body;
var showPopup = document.getElementById('show-popup');
showPopup.addEventListener('click', function(e) {
e.preventDefault();
popupContainer.classList.add('show');
});
popupContainer.addEventListener('click', function(e) {
e.stopPropagation();
});
body.addEventListener('click', function(e) {
if(popupContainer.classList.contains('show'))
popupContainer.classList.remove('show');
);
I would like to have a scroll to top arrow fixed in my page using angular bootstrap.
Currently I have
<div class="col-md-1">
<div class="affix">
<div>
<a th:href="#{/}" href="#" target="_self"><img id="image" src="source" alt="yoli" width="50px" /></a>
</div>
Scroll to top
</div>
</div>
<div class="col-md-6">
<div id="search-bar" ng-include="blabla"></div>
<li ng-repeat="something"></li>
</div>
However when the "Scroll to top" is click it only works first time since the url changes to ...#search-bar and when you click it again nothing happens. So how do I scroll to top without changing the url?
And also question how do I make the "Scroll to top" only show when the search-bar is not showing?
I was thinking about using $anchorScroll and using id'ed numbers on li and if it's higher then "element-3" then show the button, however not sure if that would work.
UPDATE:
I am thinking of following this example, that is using navigation bars that is #search and #results and make the #search href visible on #results active and #results one hidden.
You can do this without jQuery as well:
function filterPath(string) {
return string
.replace(/^\//, '')
.replace(/(index|default).[a-zA-Z]{3,4}$/, '')
.replace(/\/$/, '');
}
const locationPath = filterPath(location.pathname);
document.querySelectorAll('a[href*="#"]').forEach(link => {
let thisPath = filterPath(link.pathname) || locationPath;
if ((location.hostname == link.hostname || !link.hostname)
&& (locationPath == thisPath)
) {
let hashName = link.hash.replace(/#/, '');
if (hashName) {
let targetEl = document.getElementById(hashName);
if (targetEl) {
link.addEventListener('click', () => {
event.preventDefault();
targetEl.scrollIntoView({
top: 50,
left: 0,
behavior: "smooth"
});
});
}
}
}
});
Here is how you can do it. Create a button:
Scroll To Top
CSS:
.scrollToTop{
width:100px;
height:130px;
padding:10px;
text-align:center;
background: whiteSmoke;
font-weight: bold;
color: #444;
text-decoration: none;
position:fixed;
top:75px;
right:40px;
display:none;
background: url('arrow_up.png') no-repeat 0px 20px;
}
.scrollToTop:hover{
text-decoration:none;
}
JavaScript:
$(document).ready(function(){
//Check to see if the window is top if not then display button
$(window).scroll(function(){
if ($(this).scrollTop() > 100) {
$('.scrollToTop').fadeIn();
} else {
$('.scrollToTop').fadeOut();
}
});
//Click event to scroll to top
$('.scrollToTop').click(function(){
$('html, body').animate({scrollTop : 0},800);
return false;
});
});
You can find a demo here. The source presented is taken from here.
So this post might get lengthy but I'm stuck with iScroll. What I'm doing is populating my list with articles and when one gets clicked, I'm sliding in a div over the list to display the article. That part works but what doesn't is when I scroll through the article and get to the end, it keeps scrolling the list with articles. You can have a look here (the site is in russian but click on an article and scroll all the way to the bottom). Here's my entire code:
<head>
<style>
body{
padding: 0;
margin: 0;
border: 0;
}
#header{
position:fixed;
top:0;
left:0;
height:100px;
width: 100%;
background-color: black;
}
header{
position: absolute;
z-index: 2;
top: 0; left: 0;
width: 100%;
height: 50px;
}
#wrapper{
position: absolute;
z-index: 1;
width: 100%;
top: 52px;
left: 0;
overflow: auto;
}
#container{
position:fixed;
top:0;
right:-100%;
width:100%;
height:100%;
z-index: 10;
background-color: red;
overflow: auto;
}
#content{
margin:100px 10px 0px 10px;
}
</style>
</head>
<body>
<header>Main News</header>
<div id="wrapper">
<ul id="daily"></ul>
<ul id="exclusive"></ul>
<ul id="must"></ul>
<ul id="main"></ul>
<ul id="ukr"></ul>
<ul id="nba"></ul>
<ul id="euro"></ul>
</div>
<div id="container">
<div id="wrapper2">
<div id="header">
<button onclick="hide();">Back</button>
</div>
<div id="content"></div>
</div>
</div>
<script src="js/zepto.js"></script>
<script>
//AJAX requests to fill the li's...
function sayhi(url){
$('#container').animate({
right:'0',
}, 200, 'linear');
$.ajax({
url: serviceURL + "getnewstext.php",
data: {link: url},
success: function(content){
$('#content').append(content);
}
});
}
function hide(){
$('#container').animate({
right:'-100%'
}, 200, 'linear');
$('#content').empty();
}
</script>
<script src="js/iscroll-lite.js"></script>
<script>
var myScroll;
function scroll () {
myScroll = new iScroll('wrapper2', {hScroll: false, vScrollbar: false, bounce: false});
myScroll2 = new iScroll('wrapper', {hScroll: false, vScrollbar: false});
}
document.addEventListener('DOMContentLoaded', scroll, false);
</script>
</body>
Is there a way to scroll on the div container, or content, or wrapper2 without scrolling the wrapper div with the list of articles? Maybe I'm not using iScroll correctly? The same problem happens on Android and iPhone.
EDIT 1:
I set the wrapper position to fixed. Now the div container is the only one scrolling but the list of articles isn't scrolling...I added another iScroll to the wrapper but it's not working. Any advice here?
EDIT 2:
So I dropped iScroll all together and trying with CSS instead. To my onclick events I added:
$('body').css('overflow', 'hidden');
And when the close button is clicked I changed the overflow to auto. Now this stops the body from scrolling in a browser but not on mobile!!! How can I make it do the same thing on mobile???
I finally got it to work. What I needed to do is add another div inside the wrapper div. I'll share the code so hopefully it helps someone else Here's what the new code looks like:
<body>
<!--Added scroller div(without iScroll it works also...just make two divs so the body isn't scrolled but the second div is scrolled-->
<div id="wrapper">
<div class="scroller">
<header>Main News</header>
<ul id="daily"></ul>
<ul id="exclusive"></ul>
<ul id="must"></ul>
<ul id="main"></ul>
<ul id="ukr"></ul>
<ul id="nba"></ul>
<ul id="euro"></ul>
</div>
</div>
<div id="container">
<div class="scroller">
<div id="header">
<button onclick="hide();">Back</button>
</div>
<div id="content"></div>
</div>
</div>
<script>
$('body').on('touchmove', function(e){
e.preventDefault();
});
//prevents native scrolling so only iScroll is doing the scrolling
//after the AJAX call to get the content, declare your iScroll variable
var myScroll;
myScroll = new iScroll('wrapper');
setTimeout (function(){
myScroll.refresh();
}, 2000);
//set time out to give the page a little time to load the content and refresh your iScroll variable so it takes in the entire content of the wrapper div
var myScroll1;
myScroll1 = new iScroll('container');
//I defined my second iScroll variable here so I can destroy it in the next part...
//function sayhi(url) stays the same but in success of AJAX looks like this:
success: function(content){
$('#content').append(content);
myScroll1.destroy();
myScroll1 = null;
myScroll1 = new iScroll('container');
setTimeout (function(){
myScroll1.refresh();
}, 2000);
}
//when the div slides on the screen and content gets loaded, destroy your second iScroll
//variable, set it to null and define it all over again so it takes in the entire content
And that's it. Works perfectly now with two divs which need to use iScroll on the same page. Hope the explanation is clear enough and helps someone!!!
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