Scroll Automatically to the Bottom of the Page - javascript

I have a list of questions. When I click on the first question, it should automatically take me to a specific element at the bottom of the page.
How can I do this with jQuery?

jQuery isn't necessary. Most of the top results I got from a Google search gave me this answer:
window.scrollTo(0, document.body.scrollHeight);
Where you have nested elements, the document might not scroll. In this case, you need to target the element that scrolls and use its scroll height instead.
nestedElement.scrollTo(0, nestedElement.scrollHeight);
Some additional sources you can take a look at:
http://www.alecjacobson.com/weblog/?p=753
http://www.mediacollege.com/internet/javascript/page/scroll.html
http://www.electrictoolbox.com/jquery-scroll-bottom/

To scroll entire page to the bottom:
const scrollingElement = (document.scrollingElement || document.body);
scrollingElement.scrollTop = scrollingElement.scrollHeight;
You can view the demo here
To scroll a specific element to the bottom:
const scrollToBottom = (id) => {
const element = document.getElementById(id);
element.scrollTop = element.scrollHeight;
}
Here is the demo
And here's how it works:
Ref: scrollTop, scrollHeight, clientHeight
UPDATE: Latest versions of Chrome (61+) and Firefox does not support scrolling of body, see: https://dev.opera.com/articles/fixing-the-scrolltop-bug/

Vanilla JS implementation:
element.scrollIntoView(false);
https://developer.mozilla.org/en-US/docs/Web/API/element.scrollIntoView

You can use this to go down the page in an animation format.
$('html,body').animate({scrollTop: document.body.scrollHeight},"fast");

one liner to smooth scroll to the bottom
window.scrollTo({ left: 0, top: document.body.scrollHeight, behavior: "smooth" });
To scroll up simply set top to 0

Below should be the cross browser solution. It has been tested on Chrome, Firefox, Safari and IE11
window.scrollTo(0, document.body.scrollHeight || document.documentElement.scrollHeight);
window.scrollTo(0,document.body.scrollHeight); doesn't work on Firefox, at least for Firefox 37.0.2

Sometimes the page extends on scroll to buttom (for example in social networks), to scroll down to the end (ultimate buttom of the page) I use this script:
var scrollInterval = setInterval(function() {
document.documentElement.scrollTop = document.documentElement.scrollHeight;
}, 50);
And if you are in browser's javascript console, it might be useful to be able to stop the scrolling, so add:
var stopScroll = function() { clearInterval(scrollInterval); };
And then use stopScroll();.
If you need to scroll to particular element, use:
var element = document.querySelector(".element-selector");
element.scrollIntoView();
Or universal script for autoscrolling to specific element (or stop page scrolling interval):
var notChangedStepsCount = 0;
var scrollInterval = setInterval(function() {
var element = document.querySelector(".element-selector");
if (element) {
// element found
clearInterval(scrollInterval);
element.scrollIntoView();
} else if((document.documentElement.scrollTop + window.innerHeight) != document.documentElement.scrollHeight) {
// no element -> scrolling
notChangedStepsCount = 0;
document.documentElement.scrollTop = document.documentElement.scrollHeight;
} else if (notChangedStepsCount > 20) {
// no more space to scroll
clearInterval(scrollInterval);
} else {
// waiting for possible extension (autoload) of the page
notChangedStepsCount++;
}
}, 50);

CSS-Only?!
An interesting CSS-only alternative:
display: flex;
flex-direction: column-reverse;
/* ...probably usually along with: */
overflow-y: scroll; /* or hidden or auto */
height: 100px; /* or whatever */
It's not bullet-proof but I've found it helpful in several situations.
Documentation: flex, flex-direction, overflow-y
Demo:
var i=0, foo='Lorem Ipsum & foo in bar or blah ! on and'.split(' ');
setInterval(function(){demo.innerHTML+=foo[i++%foo.length]+' '},200)
#demo{ display:flex;
flex-direction:column-reverse;
overflow-y:scroll;
width:150px;
height:150px;
border:3px solid black; }
body{ font-family:arial,sans-serif;
font-size:15px; }
Autoscrolling demo:šŸ¾
<div id='demo'></div>

you can do this too with animation, its very simple
$('html, body').animate({
scrollTop: $('footer').offset().top
//scrollTop: $('#your-id').offset().top
//scrollTop: $('.your-class').offset().top
}, 'slow');
hope helps,
thank you

You can use this function wherever you need to call it:
function scroll_to(div){
if (div.scrollTop < div.scrollHeight - div.clientHeight)
div.scrollTop += 10; // move down
}
jquery.com: ScrollTo

So many answers trying to calculate the height of the document. But it wasn't calculating correctly for me. However, both of these worked:
jquery
$('html,body').animate({scrollTop: 9999});
or just js
window.scrollTo(0,9999);

Here is a method that worked for me:
Expected outcome:
No scroll animation
Loads at bottom of page on first load
Loads on bottom of page for all refreshes
Code:
<script>
function scrollToBottom() {
window.scrollTo(0, document.body.scrollHeight);
}
history.scrollRestoration = "manual";
window.onload = scrollToBottom;
</script>
Why this may work over other methods:
Browsers such as Chrome have a built-in preset to remember where you were on the page, after refreshing. Just a window.onload doesn't work because your browser will automatically scroll you back to where you were before refreshing, AFTER you call a line such as:
window.scrollTo(0, document.body.scrollHeight);
That's why we need to add:
history.scrollRestoration = "manual";
before the window.onload to disable that built-in feature first.
References:
Documentation for window.onload: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload
Documentation for window.scrollTo: https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo
Documentation for history.scrollRestoration: https://developer.mozilla.org/en-US/docs/Web/API/History/scrollRestoration

A simple way if you want to scroll down to a specific element.
Call this function whenever you want to scroll down.
function scrollDown() {
document.getElementById('scroll').scrollTop = document.getElementById('scroll').scrollHeight
}
ul{
height: 100px;
width: 200px;
overflow-y: scroll;
border: 1px solid #000;
}
<ul id='scroll'>
<li>Top Here</li>
<li>Something Here</li>
<li>Something Here</li>
<li>Something Here</li>
<li>Something Here</li>
<li>Something Here</li>
<li>Something Here</li>
<li>Something Here</li>
<li>Something Here</li>
<li>Something Here</li>
<li>Bottom Here</li>
<li style="color: red">Bottom Here</li>
</ul>
<br />
<button onclick='scrollDown()'>Scroll Down</button>

You can attach any id to reference attribute href of link element:
<a href="#myLink" id="myLink">
Click me
</a>
In the example above when user clicks Click me at the bottom of page, navigation navigates to Click me itself.

You may try Gentle Anchors a nice javascript plugin.
Example:
function SomeFunction() {
// your code
// Pass an id attribute to scroll to. The # is required
Gentle_Anchors.Setup('#destination');
// maybe some more code
}
Compatibility Tested on:
Mac Firefox, Safari, Opera
Windows Firefox, Opera, Safari, Internet Explorer 5.55+
Linux untested but should be fine with Firefox at least

Late to the party, but here's some simple javascript-only code to scroll any element to the bottom:
function scrollToBottom(e) {
e.scrollTop = e.scrollHeight - e.getBoundingClientRect().height;
}

For Scroll down in Selenium use below code:
Till the bottom drop down, scroll till the height of the page.
Use the below javascript code that would work fine in both, JavaScript and React.
JavascriptExecutor jse = (JavascriptExecutor) driver; // (driver is your browser webdriver object)
jse.executeScript("window.scrollBy(0,document.body.scrollHeight || document.documentElement.scrollHeight)", "");

Here's my solution:
//**** scroll to bottom if at bottom
function scrollbottom() {
if (typeof(scr1)!='undefined') clearTimeout(scr1)
var scrollTop = (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
var scrollHeight = (document.documentElement && document.documentElement.scrollHeight) || document.body.scrollHeight;
if((scrollTop + window.innerHeight) >= scrollHeight-50) window.scrollTo(0,scrollHeight+50)
scr1=setTimeout(function(){scrollbottom()},200)
}
scr1=setTimeout(function(){scrollbottom()},200)

I have an Angular app with dynamic content and I tried several of the above answers with not much success. I adapted #Konard's answer and got it working in plain JS for my scenario:
HTML
<div id="app">
<button onClick="scrollToBottom()">Scroll to Bottom</button>
<div class="row">
<div class="col-md-4">
<br>
<h4>Details for Customer 1</h4>
<hr>
<!-- sequence Id -->
<div class="form-group">
<input type="text" class="form-control" placeholder="ID">
</div>
<!-- name -->
<div class="form-group">
<input type="text" class="form-control" placeholder="Name">
</div>
<!-- description -->
<div class="form-group">
<textarea type="text" style="min-height: 100px" placeholder="Description" ></textarea>
</div>
<!-- address -->
<div class="form-group">
<input type="text" class="form-control" placeholder="Address">
</div>
<!-- postcode -->
<div class="form-group">
<input type="text" class="form-control" placeholder="Postcode">
</div>
<!-- Image -->
<div class="form-group">
<img style="width: 100%; height: 300px;">
<div class="custom-file mt-3">
<label class="custom-file-label">{{'Choose file...'}}</label>
</div>
</div>
<!-- Delete button -->
<div class="form-group">
<hr>
<div class="row">
<div class="col">
<button class="btn btn-success btn-block" data-toggle="tooltip" data-placement="bottom" title="Click to save">Save</button>
<button class="btn btn-success btn-block" data-toggle="tooltip" data-placement="bottom" title="Click to update">Update</button>
</div>
<div class="col">
<button class="btn btn-danger btn-block" data-toggle="tooltip" data-placement="bottom" title="Click to remove">Remove</button>
</div>
</div>
<hr>
</div>
</div>
</div>
</div>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
JS
function scrollToBottom() {
scrollInterval;
stopScroll;
var scrollInterval = setInterval(function () {
document.documentElement.scrollTop = document.documentElement.scrollHeight;
}, 50);
var stopScroll = setInterval(function () {
clearInterval(scrollInterval);
}, 100);
}
Tested on the latest Chrome, FF, Edge, and stock Android browser. Here's a fiddle:
https://jsfiddle.net/cbruen1/18cta9gd/16/

I found a trick to make it happen.
Put an input type text at the bottom of the page and call a jquery focus on it whenever you need to go at the bottom.
Make it readonly and nice css to clear border and background.

If any one searching for Angular
you just need to scroll down add this to your div
#scrollMe [scrollTop]="scrollMe.scrollHeight"
<div class="my-list" #scrollMe [scrollTop]="scrollMe.scrollHeight">
</div>

This will guaranteed scroll to the bottom
Head Codes
<script src="http://code.jquery.com/jquery-1.8.1.min.js"></script>
<script language="javascript" type="text/javascript">
function scrollToBottom() {
$('#html, body').scrollTop($('#html, body')[0].scrollHeight);
}
</script>
Body code
ā–¼ Bottom ā–¼

I've had the same issue. For me at one point in time the div's elements were not loaded entirely and the scrollTop property was initialized with the current value of scrollHeight, which was not the correct end value of scrollHeight.
My project is in Angular 8 and what I did was:
I used viewchild in order to obtain the element in my .ts file.
I've inherited the AfterViewChecked event and placed one line of code in there which states that the viewchild element has to take into the scrollTop value the value of scrollHeight (this.viewChildElement.nativeElement.scrollTop = this.viewChildElement.nativeElement.scrollHeight;)
The AfterViewChecked event fires a few times and it gets in the end the proper value from scrollHeight.

We can use ref and by getElementById for scrolling specific modal or page .
const scrollToBottomModel = () => {
const scrollingElement = document.getElementById("post-chat");
scrollingElement.scrollTop = scrollingElement.scrollHeight;
};
In the modal body you can call above function
<Modal.Body
className="show-grid"
scrollable={true}
style={{
maxHeight: "calc(100vh - 210px)",
overflowY: "auto",
height: "590px",
}}
ref={input => scrollToBottomModel()}
id="post-chat"
>
will work this

A simple example with jquery
$('html, body').animate({
scrollTop: $(this).height(),
});

I gave up with scrollto but instead tried anchor approach:
scroll to the bottom
Along with this CSS charm:
html,
body {
scroll-behavior: smooth;
}
Have a nice day!

If there is an ID in any kind of tag at or nearby where you want to scroll to, then all it takes is one line of JavaScript making use of the scrollIntoView function. For example, let's say your element in question is a DIV with the ID "mydiv1"
<div id="mydiv1">[your contents]</div>
then you would run the JavaScript command
document.getElementById("mydiv1").scrollIntoView();
No JQuery is necessary at all.
Hope this helps.

window.scrollTo(0,1e10);
always works.
1e10 is a big number. so its always the end of the page.

A picture is worth a thousand words:
The key is:
document.documentElement.scrollTo({
left: 0,
top: document.documentElement.scrollHeight - document.documentElement.clientHeight,
behavior: 'smooth'
});
It is using document.documentElement, which is the <html> element. It is just like using window, but it is just my personal preference to do it this way, because if it is not the whole page but a container, it works just like this except you'd change document.body and document.documentElement to document.querySelector("#container-id").
Example:
let cLines = 0;
let timerID = setInterval(function() {
let elSomeContent = document.createElement("div");
if (++cLines > 33) {
clearInterval(timerID);
elSomeContent.innerText = "That's all folks!";
} else {
elSomeContent.innerText = new Date().toLocaleDateString("en", {
dateStyle: "long",
timeStyle: "medium"
});
}
document.body.appendChild(elSomeContent);
document.documentElement.scrollTo({
left: 0,
top: document.documentElement.scrollHeight - document.documentElement.clientHeight,
behavior: 'smooth'
});
}, 1000);
body {
font: 27px Arial, sans-serif;
background: #ffc;
color: #333;
}
You can compare the difference if there is no scrollTo():
let cLines = 0;
let timerID = setInterval(function() {
let elSomeContent = document.createElement("div");
if (++cLines > 33) {
clearInterval(timerID);
elSomeContent.innerText = "That's all folks!";
} else {
elSomeContent.innerText = new Date().toLocaleDateString("en", {
dateStyle: "long",
timeStyle: "medium"
});
}
document.body.appendChild(elSomeContent);
}, 1000);
body {
font: 27px Arial, sans-serif;
background: #ffc;
color: #333;
}

Related

Run Jquery only when an element is in the viewport

I'm trying to perform the Jquery function below when the element becomes visible in the viewport rather than on the page load. What would I need to change to allow that to happen? I'm using an external JS file to perform the Jquery, so keep that in mind.
Here's a piece of the HTML that is associated with the Jquery function -
<div class="skillbar clearfix " data-percent="70%">
<div class="skillbar-title" style="background: #FF704D;">
<span>Illustrator</span></div>
<div class="skillbar-bar" style="background: #FF704D;"></div>
<div class="skill-bar-percent">70%</div>
</div>
jQuery(document).ready(function(){
jQuery('.skillbar').each(function(){
jQuery(this).find('.skillbar-bar').animate({
width:jQuery(this).attr('data-percent')
},4000);
});
});
I once came across such problem and what I used is waypoints small library.
all you need is to include this library and do:
var waypoint = new Waypoint({
element: document.getElementById('waypoint'),
handler: function(direction) {
console.log('Element is in viewport');
}
})
Using CSS3 transitions instead of jQuery animations might be more performant and simpler. a cheap and nasty way of pushing it out of screen to demonstarate the effect.
There's a couple of things you'll need to do - firstly if you only want the animation to trigger when it's in the viewport then you'll need to check if anything is in the viewport on scroll. Then only update the bars width when it comes into view. If you want the effect to repeat every time it comes into viewport you'll need to set .skillbar-bar's width back to 0 if it's out of the viewport (just add an else statement to the viewport checking if)
I've added a 1000px margin-top and 400px margin-bottom in my example to .skillbar as a cheap and nasty way of demonstrating the effect
(function($){
$(document).ready(function(){
var $els = $('.skillbar'); // Note this must be moved to within event handler if dynamically adding elements - I've placed it for performance reasons
var $window = $(window);
$window.on('scroll', function(){
$els.each(function(){ // Iterate over all skillbars
var $this = $(this);
if($window.scrollTop() > $this.offset().top - $window.height()){ // Check if it's in viewport
$this.find('.skillbar-bar').css({'width' : $this.attr('data-percent')}); // Update the view with percentage
}
});
});
});
}(jQuery));
.skillbar{
margin-top: 1000px;
margin-bottom: 400px;
position: relative
}
.skillbar-bar{
transition: width 4s;
position: absolute;
height: 20px;
}
.skill-bar-percent{
position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Scroll down 1000px :)
<div class="skillbar clearfix " data-percent="70%">
<div class="skillbar-title">
<span>Illustrator</span></div>
<div class="skillbar-bar" style="background: #FF704D; width: 20%"></div>
<div class="skill-bar-percent">70%</div>
</div>
This might work for you.
var el = $('.yourElement'),
offset = el.offset(),
scrollTop = $(window).scrollTop();
//Check for scroll position
if ((scrollTop > offset.top)) {
// Code..
}

Scrolling a DIV to Specific Location

There is a plethora of similar questions around but none of them seem to be looking for what I'm looking for, or else none of the answers are useful for my purposes.
The jsfiddle: http://jsfiddle.net/tumblingpenguin/9yGCf/4/
The user will select an option and the page will reload with their option applied. What I need is for the "option list" DIV to be scrolled down to the selected option such that it is in the center of the option list.
The HTML...
<div id="container">
<a href="#">
<div class="option">
Option 1
</div>
</a>
<!-- other options -->
<a href="#">
<div class="option selected"> <!-- scroll to here -->
Option 4
</div>
<!-- other options -->
<a href="#">
<div class="option">
Option 7
</div>
</a>
</div>
The selected option is marked with the selected class. I need to somehow scroll the DIV down to the selected option.
The CSS...
#container {
background-color: #F00;
height: 100px;
overflow-x: hidden;
overflow-y: scroll;
width: 200px;
}
a {
color: #FFF;
text-decoration: none;
}
.option {
background-color: #c0c0c0;
padding: 5px;
width: 200px;
}
.option:hover {
background-color: #ccc;
}
.selected {
background-color: #3c6;
}
I've seen this done on other websites so I know it's possibleā€”I just haven't a clue where to begin with it.
P.S. jQuery solutions are acceptable.
Something like this http://jsfiddle.net/X2eTL/1/:
// On document ready
$(function(){
// Find selected div
var selected = $('#container .selected');
// Scroll container to offset of the selected div
selected.parent().parent().scrollTop(selected[0].offsetTop);
});
Without the jQuery (put this at the bottom of the < body > tag:
// Find selected div
var selected = document.querySelector('#container .selected');
// Scroll container to offset of the selected div
selected.parentNode.parentNode.scrollTop = selected.offsetTop;
demo: http://jsfiddle.net/66tGt/
Since you said JQuery answers are acceptable, here's an example of what you're looking for:
$('body, html').animate({ scrollTop: div.offset().top-210 }, 1000);
Replace div for whatever element you want to scroll to.
Here is one possible solution that may work for you:
Demo Fiddle
JS:
$('#container').scrollTop( $('.selected').position().top );
Take a look at this fiddle : http://jsfiddle.net/9yGCf/8/
As requested it scrolls to the middle of the div (you can change the offset by however much you want to make little adjustments). I would probably suggest setting either a line height with some padding and whatnot and then do the math to change the offset that I have at -40 so that it does put it in the middle.
But I used jquery and came up with this quick little code... also added some code to change the selected option
$('.option').click(function(){
$('.selected').removeClass('selected');
$(this).addClass('selected');
$(this).parent().parent().scrollTop(selected[0].offsetTop - 40);
});
This magical API will automatically scroll to the right position.
element.scrollIntoView({ block: 'center' })
See more details:
https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

How to scroll back to the top of page on button click?

I am creating my product pages by using the object tag code, but every time I click the "view" button, the next page is staying at the same position of previous page which I just viewed. How can I add functionality that will let me view from the top of page every time I click the "view" button?
<div id="container" class="clearfix"><!--! end of #sidebar -->
<div class="holder"></div>
<div id="content" class="defaults"><!-- navigation holder -->
<div id="title2">Office Section</div>
<!-- item container -->
<ul id="itemContainer">
<li>
<div id="product">
<div id="title">FuBangĀ®</div>
<div class="imageOuter" style="margin:0">
<a class="image" href="officesection010.html">
<span class="rollover" ></span>
<img class="imgborder" src="product/officesection/010.jpg" width="165" height="165" />
</a>
</div><br />
<div id="text">Sofa </div><br />
<div id="button">
View Details
</div>
</div>
</li>
</ul>
<br />
<div id="title2"></div>
<div class="holder"></div>
</div>
</div> <!--! end of #content -->
</div> <!--! end of #container -->
When I click the "View Details" button at a specific position "x" here: http://postimg.org/image/vgs0lwhtr/
The next page shows the same position "x", but I want it to jump to the top of page:
http://postimg.org/image/vn80e2lph/
Using Javascript:
document.body.scrollTop = document.documentElement.scrollTop = 0;
Using jQuery:
$(function() {
$('body').scrollTop(0);
});
jQuery(document).ready(function($){
$(window).scroll(function(){
if ($(this).scrollTop() > 50) {
$('#backToTop').fadeIn('slow');
} else {
$('#backToTop').fadeOut('slow');
}
});
$('#backToTop').click(function(){
$("html, body").animate({ scrollTop: 0 }, 500);
//$("html, body").scrollTop(0); //For without animation
return false;
});
});
please refere this, may this help
Sometimes placing scroll to body doesn't work if your current content is generated through jQuery (as it was in my case). In such situation you can just do following.
$(function() {
$('html').scrollTop(0);
});
A small issue with Subhash's jQuery solution is that you must call this code within $(document).ready() in order for your $('body') selector to work. The ready event may not fire before parts of your page have been rendered to the screen.
An better approach is to simply modify the user's location as a work-around to this browser 'feature':
//Above all of your $(document).ready(...) code
document.location = "#";
Simple HTML solution for jumping between page parts
// Place a tag like this where you would like to go
// in your case at the top
<a name="top"></a>
// you will reach there by click of this link better use an image reach their by clicking on this we can also use an image, align in right
last
Back to top button, works in all browsers.To change the scroll speed simply change the x in counter -= x here x = 10
function scrollToTop(){
var myBody = document.body;
var id = setInterval(secondFunction,1);
var height = window.pageYOffset;
var counter = height;
function secondFunction(){
if(window.pageYOffset == 0){
clearInterval(id);
}
else {
if(!!navigator.userAgent.match(/Trident/g) || !!navigator.userAgent.match(/MSIE/g)){
counter -= 10;
counter--;
document.documentElement.scrollTop = counter;
}
else {
counter -= 10;
counter--;
myBody.scrollTop = counter;
}
}
}
}
body {
height: 5000px;
margin: 0;
padding: 0;
}
.backToTop {
position: fixed;
/* Fixed at page */
top: auto;
bottom: 20px;
left: auto;
right: 20px;
background-color: crimson;
color: white;
padding: 5px;
cursor: pointer;
}
header {
position: relative;
top: 0;
left: 0;
width: 100%;
height: 100px;
background-color: black;
}
<!-- back to top button -->
<span class="backToTop" onclick="scrollToTop()">TOP</span>
<!-- Header -->
<header>
</header>
Assign an id="#body" and tabindex in the <body> tag
<body id="#body" tabindex="1">
and use jquery focus()
$(function() {
$("#body").attr("tabindex",-1).focus();
}
You can use this method:
function gototop() {
if (window.scrollY>0) {
window.scrollTo(0,window.scrollY-20)
setTimeout("gototop()",10)
}
}

JQuery show and hide div on mouse click (animate)

This is my HTML code:
<div id="showmenu">Click Here</div>
<div class="menu" style="display: none;">
<ul>
<li>Button1</li>
<li>Button2</li>
<li>Button3</li>
</ul>
</div>
And I want to show .menu on click on #showmenu sliding from left to right (with animate). On click again on #showmenu or anywhere in site page, .menu will hide (slide back to left).
I use JQuery 2.0.3
I've tried this, but it doesn't do what I want.
$(document).ready(function() {
$('#showmenu').toggle(
function() {
$('.menu').slideDown("fast");
},
function() {
$('.menu').slideUp("fast");
}
);
});
That .toggle() method was removed from jQuery in version 1.9. You can do this instead:
$(document).ready(function() {
$('#showmenu').click(function() {
$('.menu').slideToggle("fast");
});
});
Demo: http://jsfiddle.net/APA2S/1/
...but as with the code in your question that would slide up or down. To slide left or right you can do the following:
$(document).ready(function() {
$('#showmenu').click(function() {
$('.menu').toggle("slide");
});
});
Demo: http://jsfiddle.net/APA2S/2/
Noting that this requires jQuery-UI's slide effect, but you added that tag to your question so I assume that is OK.
Of course slideDown and slideUp don't do what you want, you said you want it to be left/right, not top/down.
If your edit to your question adding the jquery-ui tag means you're using jQuery UI, I'd go with nnnnnn's solution, using jQuery UI's slide effect.
If not:
Assuming the menu starts out visible (edit: oops, I see that isn't a valid assumption; see note below), if you want it to slide out to the left and then later slide back in from the left, you could do this: Live Example | Live Source
$(document).ready(function() {
// Hide menu once we know its width
$('#showmenu').click(function() {
var $menu = $('.menu');
if ($menu.is(':visible')) {
// Slide away
$menu.animate({left: -($menu.outerWidth() + 10)}, function() {
$menu.hide();
});
}
else {
// Slide in
$menu.show().animate({left: 0});
}
});
});
You'll need to put position: relative on the menu element.
Note that I replaced your toggle with click, because that form of toggle was removed from jQuery.
If you want the menu to start out hidden, you can adjust the above. You want to know the element's width, basically, when putting it off-page.
This version doesn't care whether the menu is initially-visible or not: Live Copy | Live Source
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<div id="showmenu">Click Here</div>
<div class="menu" style="display: none; position: relative;"><ul><li>Button1</li><li>Button2</li><li>Button3</li></ul></div>
<script>
$(document).ready(function() {
var first = true;
// Hide menu once we know its width
$('#showmenu').click(function() {
var $menu = $('.menu');
if ($menu.is(':visible')) {
// Slide away
$menu.animate({left: -($menu.outerWidth() + 10)}, function() {
$menu.hide();
});
}
else {
// Slide in
$menu.show().css("left", -($menu.outerWidth() + 10)).animate({left: 0});
}
});
});
</script>
</body>
</html>
I would do something like this
DEMO in JsBin: http://jsbin.com/ofiqur/1/
Click Here
<div class="menu">
<ul>
<li>Button 1</li>
<li>Button 2</li>
<li>Button 3</li>
</ul>
</div>
and in jQuery as simple as
var min = "-100px", // remember to set in css the same value
max = "0px";
$(function() {
$("#showmenu").click(function() {
if($(".menu").css("marginLeft") == min) // is it left?
$(".menu").animate({ marginLeft: max }); // move right
else
$(".menu").animate({ marginLeft: min }); // move left
});
});
Try this:
<script type="text/javascript">
$.fn.toggleFuncs = function() {
var functions = Array.prototype.slice.call(arguments),
_this = this.click(function(){
var i = _this.data('func_count') || 0;
functions[i%functions.length]();
_this.data('func_count', i+1);
});
}
$('$showmenu').toggleFuncs(
function() {
$( ".menu" ).toggle( "drop" );
},
function() {
$( ".menu" ).toggle( "drop" );
}
);
</script>
First fuction is an alternative to JQuery deprecated toggle :) . Works good with JQuery 2.0.3 and JQuery UI 1.10.3
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".click-header").click(function(){
$(this).next(".hidden-content").slideToggle("slow");
$(this).toggleClass("expanded-header");
});
});
</script>
.demo-container {
margin:0 auto;
width: 600px;
text-align:center;
}
.click-header {
padding: 5px 10px 5px 60px;
background: url(images/arrow-down.png) no-repeat 50% 50%;
}
.expanded-header {
padding: 5px 10px 5px 60px;
background: url(images/arrow-up.png) no-repeat 50% 50%;
}
.hidden-content {
display:none;
border: 1px solid #d7dbd8;
padding: 20px;
text-align: center;
}
<div class="demo-container">
<div class="click-header"> </div>
<div class="hidden-content">Lorem Ipsum.</div>
</div>
Use slideToggle(500) function with a duration in milliseconds for getting a better effect.
Sample Html
<body>
<div class="growth-step js--growth-step">
<div class="step-title">
<div class="num">2.</div>
<h3>How Can Aria Help Your Business</h3>
</div>
<div class="step-details ">
<p>At Aria solutions, weā€™ve taken the consultancy concept one step further by offering a full service
management organization with expertise. </p>
</div>
</div>
<div class="growth-step js--growth-step">
<div class="step-title">
<div class="num">3.</div>
<h3>How Can Aria Help Your Business</h3>
</div>
<div class="step-details">
<p>At Aria solutions, weā€™ve taken the consultancy concept one step further by offering a full service
management organization with expertise. </p>
</div>
</div>
</body>
In your js file, if you need child propagation for the animation then remove the second click event function and its codes.
$(document).ready(function(){
$(".js--growth-step").click(function(event){
$(this).children(".step-details").slideToggle(500);
return false;
});
//for stoping child to manipulate the animation
$(".js--growth-step .step-details").click(function(event) {
event.stopPropagation();
});
});

How to scroll to an element inside a div?

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

Categories

Resources