How to scroll to specific item using jQuery? - javascript

I have a big table with vertical scroll bar.
I would like to scroll to a specific line in this table using jQuery/JavaScript.
Are there built-in methods to do this?
Here is a little example to play with.
div {
width: 100px;
height: 70px;
border: 1px solid blue;
overflow: auto;
}
<div>
<table id="my_table">
<tr id='row_1'><td>1</td></tr>
<tr id='row_2'><td>2</td></tr>
<tr id='row_3'><td>3</td></tr>
<tr id='row_4'><td>4</td></tr>
<tr id='row_5'><td>5</td></tr>
<tr id='row_6'><td>6</td></tr>
<tr id='row_7'><td>7</td></tr>
<tr id='row_8'><td>8</td></tr>
<tr id='row_9'><td>9</td></tr>
</table>
</div>

Dead simple. No plugins needed.
var $container = $('div'),
$scrollTo = $('#row_8');
$container.scrollTop(
$scrollTo.offset().top - $container.offset().top + $container.scrollTop()
);
// Or you can animate the scrolling:
$container.animate({
scrollTop: $scrollTo.offset().top - $container.offset().top + $container.scrollTop()
});​
Here is a working example.
Documentation for scrollTop.

I realise this doesn't answer scrolling in a container but people are finding it useful so:
$('html,body').animate({scrollTop: some_element.offset().top});
We select both html and body because the document scroller could be on either and it is hard to determine which. For modern browsers you can get away with $(document.body).
Or, to go to the top of the page:
$('html,body').animate({scrollTop: 0});
Or without animation:
$(window).scrollTop(some_element.offset().top);
OR...
window.scrollTo(0, some_element.offset().top); // native equivalent (x, y)

I agree with Kevin and others, using a plugin for this is pointless.
window.scrollTo(0, $("#element").offset().top);

I managed to do it myself. No need for any plugins. Check out my gist:
// Replace #fromA with your button/control and #toB with the target to which
// You wanna scroll to.
//
$("#fromA").click(function() {
$("html, body").animate({ scrollTop: $("#toB").offset().top }, 1500);
});

You can use scrollIntoView() method in javascript.
just give id.scrollIntoView();
For example
row_5.scrollIntoView();

You can use the the jQuery scrollTo plugin plugin:
$('div').scrollTo('#row_8');

Scroll element to center of container
To bring the element to the center of the container.
DEMO on CODEPEN
JS
function scrollToCenter() {
var container = $('.container'),
scrollTo = $('.5');
container.animate({
//scrolls to center
scrollTop: scrollTo.offset().top - container.offset().top + scrollTo.scrollTop() - container.height() / 2
});
}
HTML
<div class="container">
<div class="1">
1
</div>
<div class="2">
2
</div>
<div class="3">
3
</div>
<div class="4">
4
</div>
<div class="5">
5
</div>
<div class="6">
6
</div>
<div class="7">
7
</div>
<div class="8">
8
</div>
<div class="9">
9
</div>
<div class="10">
10
</div>
</div>
<br>
<br>
<button id="scroll" onclick="scrollToCenter()">
Scroll
</button>
css
.container {
height: 60px;
overflow-y: scroll;
width 60px;
background-color: white;
}
It is not exact to the center but you will not recognice it on larger bigger elements.

You can scroll by jQuery and JavaScript
Just need two element jQuery and this JavaScript code :
$(function() {
// Generic selector to be used anywhere
$(".js-scroll-to-id").click(function(e) {
// Get the href dynamically
var destination = $(this).attr('href');
// Prevent href=“#” link from changing the URL hash (optional)
e.preventDefault();
// Animate scroll to destination
$('html, body').animate({
scrollTop: $(destination).offset().top
}, 1500);
});
});
$(function() {
// Generic selector to be used anywhere
$(".js-scroll-to-id").click(function(e) {
// Get the href dynamically
var destination = $(this).attr('href');
// Prevent href=“#” link from changing the URL hash (optional)
e.preventDefault();
// Animate scroll to destination
$('html, body').animate({
scrollTop: $(destination).offset().top
}, 1500);
});
});
#pane1 {
background: #000;
width: 400px;
height: 400px;
}
#pane2 {
background: #ff0000;
width: 400px;
height: 400px;
}
#pane3 {
background: #ccc;
width: 400px;
height: 400px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="nav">
<li>
Item 1
</li>
<li>
Item 2
</li>
<li>
Item 3
</li>
</ul>
<div id="pane1"></div>
<div id="pane2"></div>
<div id="pane3"></div>
<!-- example of a fixed nav menu -->
<ul class="nav">
<li>
Item 1
</li>
<li>
Item 2
</li>
<li>
Item 3
</li>
</ul>

Not sure why no one says the obvious, as there's a built in javascript scrollTo function:
scrollTo( $('#element').position().top );
Reference.

I did a combination of what others have posted. Its simple and smooth
$('#myButton').click(function(){
$('html, body').animate({
scrollTop: $('#scroll-to-this-element').position().top },
1000
);
});

Contrary to what most people here are suggesting, I'd recommend you do use a plugin if you want to animate the move. Just animating scrollTop is not enough for a smooth user experience. See my answer here for the reasoning.
I have tried a number of plugins over the years, but eventually written one myself. You might want to give it a spin: jQuery.scrollable. Using that, the scroll action becomes
$container.scrollTo( targetPosition );
But that's not all. We need to fix the target position, too. The calculation you see in other answers,
$target.offset().top - $container.offset().top + $container.scrollTop()
mostly works but is not entirely correct. It doesn't handle the border of the scroll container properly. The target element is scrolled upwards too far, by the size of the border. Here is a demo.
Hence, a better way to calculate the target position is
var target = $target[0],
container = $container[0];
targetPosition = $container.scrollTop() + target.getBoundingClientRect().top - container.getBoundingClientRect().top - container.clientTop;
Again, have a look at the demo to see it in action.
For a function which returns the target position and works for both window and non-window scroll containers, feel free to use this gist. The comments in there explain how the position is calculated.
In the beginning, I have said it would be best to use a plugin for animated scrolling. You don't need a plugin, however, if you want to jump to the target without a transition. See the answer by #James for that, but make sure you calculate the target position correctly if there is a border around the container.

For what it's worth, this is how I managed to achieve such behavior for a general element which can be inside a DIV with scrolling (without knowing the container)
It creates a fake input of the height of the target element, and then puts a focus to it, and the browser will take care about the rest no matter how deep within the scrollable hierarchy you are. Works like a charm.
var $scrollTo = $('#someId'),
inputElem = $('<input type="text"></input>');
$scrollTo.prepend(inputElem);
inputElem.css({
position: 'absolute',
width: '1px',
height: $scrollTo.height()
});
inputElem.focus();
inputElem.remove();

I did this combination. its work for me. but facing one issue if click
move that div size is too large that scenerio scroll not down to this
particular div.
var scrollDownTo =$("#show_question_" + nQueId).position().top;
console.log(scrollDownTo);
$('#slider_light_box_container').animate({
scrollTop: scrollDownTo
}, 1000, function(){
});
}

Related

Move from a <div> to another <div> on scroll

I want my #logo-page div to move smoothly to #content div on scroll and also when clicked on FontAwesome icon. How do I do that using jQuery?
<div class="english-container" id="logo-page">
<div class="title">
<h1>Mean Design.</h1>
<img class="img-responsive" id="logo" src="MeanDesignLogo.png">
<h3>ui/ux • web design • graphic design • illustration</h3>
</div> <!-- title -->
<i class="fa fa-arrow-circle-down fa-3x" aria-hidden="true"></i>
</div>
<div class="english-container" ></div>
I found a trick on how to do that at this page:
https://css-tricks.com/snippets/jquery/smooth-scrolling/
Here are two demos:
https://css-tricks.com/examples/SmoothPageScroll/
http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_eff_animate_smoothscroll
This is the example of the second demo:
$(document).ready(function(){
// Add smooth scrolling to all links
$("a").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
body, html, .main {
height: 100%;
}
section {
min-height: 100%;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
Click Me to Smooth Scroll to Section 2 Below
<div class="main">
<section></section>
</div>
<div class="main" id="section2">
<section style="background-color:blue"></section>
</div>
</body>
</html>
You guys completely ignored his question. His question was he wants to scroll from one div to another div when on scroll not on click.
window.addEventListener('scroll', () => {
document.querySelector('#mission').scrollIntoView({
behavior: 'smooth'
});
})
This will help if you want to scroll to the div with the id name "mission"
You can use following code for scrolling smoothly to #logo-page div on click of .fa-arrow-circle-down:
$(".fa-arrow-circle-down").on("click", function(e){
$("html, body").animate({'scrollTop': $("#logo-page").offset().top }, 1000 );
});//click

Add class to appropriate nav tab when cooresponding div is scrolled into

I have read similar questions and researched scrollspy, but I don't believe it will do quite what I'm looking for, since as far as I can tell it can only use bootstrap style highlighting. (If it can do more please let me know!)
I have a 4-tab navbar (usually fixed top) and a single-page site. Each tab corresponds to a different section of the page, and each section has a different background color. What I'd like to do is change the tab color to be the same as the corresponding section's background color whenever that region is scrolled to (so it will only change color once the new section's top reaches the navbar's bottom.) I have achieved this effect only when the tab is clicked, triggering a scroll event and adding an active class, however the active tab will then remain if clicking is not used, creating the problem.
Is there a way to change a variable based off the current scroll location? I have tried what I can think of but it hasn't worked yet.
JS
$(window).on('scroll', function () {
if ($(window).scrollTop() >= $('#homeContainer').height()) {
$('.menuDiv').addClass('fixed');
} else {
$('.menuDiv').removeClass('fixed');
}
});
$("#menuHomeButton").click(function(e){
$('html, body').animate({
scrollTop: $('#homeContainer').offset().top
}, 'slow');
});
$("#menuAboutButton").click(function(e){
$('html, body').animate({
scrollTop: $('#aboutContainer').offset().top + 1
}, 'slow');
});
$("#menuPortfolioButton").click(function(e){
$('html, body').animate({
scrollTop: $('#portfolioContainer').offset().top - $('.menuDiv').height() + 1
}, 'slow');
});
$("#menuContactButton").click(function(e){
$('html, body').animate({
scrollTop: $('#contactContainer').offset().top - $('.menuDiv').height() + 1
}, 'slow');
});
HTML
<div class="mainContainer">
<div class="container blue" id="homeContainer">
</div>
<div class="menuDiv"><!--
--><div class="menuItem" id="menuHomeButton" ng-class="{'active':selectedTab === 'home'}" ng-click="selectedTab = 'home'">
<div class="menuTextDiv"><p>Home</p></div><div class="menuItemColor blue"></div>
</div><!--
--><div class="menuItem" id="menuAboutButton" ng-class="{'active2':selectedTab === 'about'}" ng-click="selectedTab = 'about'">
<div class="menuTextDiv"><p>About</p></div><div class="menuItemColor blue2"></div>
</div><!--
--><div class="menuItem" id="menuPortfolioButton" ng-class="{'active3':selectedTab === 'portfolio'}" ng-click="selectedTab = 'portfolio'">
<div class="menuTextDiv"><p>Portfolio</p></div><div class="menuItemColor blue3"></div>
</div><!--
--><div class="menuItem" id="menuContactButton" ng-class="{'active4':selectedTab === 'contact'}" ng-click="selectedTab = 'contact'">
<div class="menuTextDiv"><p>Contact</p></div><div class="menuItemColor blue4"></div>
</div><!--
--></div>
<div class="container blue2" id="aboutContainer">
</div>
<div class="container blue3" id="portfolioContainer">
</div>
<div class="container blue4" id="contactContainer">
</div>
<div class="container">
</div>
</div>
Here is a fiddle, but for some reason I couldn't get the ng-click and ng-class to work on it, which changes the tab color.
Here are some images of what it looks like not on js fiddle:
What I want and have:
http://i.gyazo.com/3c7d6d80a9a490b31e795cacebbaa1a0.png
http://i.gyazo.com/1bd597080bdba6ffa34fe18cf5462b74.png
What I don't want but still also have:http://i.gyazo.com/d066effabd276d978e4775666a3b5d6c.png
If anyone has a solution I'd be extremely greatful! Thank you!
Get the distance of the div from top:
distance = $("div").scrollTop()
note: do not use var when declaring distance because than you can't access it inside a function
Then check if div has reached the top and add class:
$(window).on('scroll', function () {
if(distance - $("div").scrollTop() >= distance ){
//do something
}
});

Scrolling to a specific div using window.onload without adding to the web address

I am creating a page with 5 divs. I am using the following JavaScript code to smoothly move between them horizontaly :
$(function () {
$('ul.nav a').bind('click', function (event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollLeft: $($anchor.attr('href')).offset().left
}, 1500,'easeInOutExpo');
event.preventDefault();
});
});
The Divs are something like this:
<div class="section white" id="section5">
<h2>Technologies</h2>
<p>
text
</p>
<ul class="nav">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
</div>
I want to start with div # 3 on page load. The only solution that worked is the onload function:
window.onload = window.location.hash = 'section3';
but unfortunately when I load the page the url address is
http://localhost:51551/trial1/MainPage.aspx#section3
even when I click on another page anchors (div) and go there the URL is stuck to MainPage.aspx#section3.
I tried the solutions here: jQuery: how to scroll to certain anchor/div on page load?
But I think because I am already using Javascript to navigate the divs, its not working. I want to Either:
Remove the address #section3 part and keep using the onload
function
Even better navigate to section3 at start and have
the url change when I change the section
I am using Visual Studio 2010 Express, with ASP.NET, JS and C#. on Windows 8.1
First the following important distinction:
jQuery's #section1 selector looks for an HTML element with ID "section1", i.e. <div id="section1"></div>
The a href's #section1 URL hash looks for an anchor with name "section1", i.e. <a name="section1"></a>
This is a major difference that you need to check and understand. So you would normally need:
<a name="section1"></a>
<div id="section1">... your content here ...</div>
But since you are scrolling horizontally, I am going to do this without the <a name=...></a> part and deal with the hash in the window load handler, as I will explain further down.
Next is, I would avoid naming a JavaScript variable "event" as that looks an awful lot like a keyword, so try renaming it to ev.
If you want the click handler (the function you bind to the click event) to not follow the link clicked on, that function should return false:
$('ul.nav a').click(function (ev) {
var anchor = $(this);
$('.viewport').stop().animate({
scrollLeft: $($(anchor).attr('href')).offset().left
}, 1500,'easeInOutExpo');
// Add the section ID to the URL
window.location.hash = $(anchor).attr('href').substring(1);
ev.preventDefault();
return false;
});
Then, I'd suggest you to move the <ul class="nav">...</ul> outside of the section divs, so you don't have to repeat it inside your divs. Because you seem to be scrolling left/right, I assume you are floating your section divs next to each other in a wide container:
<div class="viewport">
<div class="container clearfix">
<div class="section" id="section1">
<h2>Technologies</h2>
<p>Text</p>
</div>
<div class="section" id="section2">
... content ...
</div>
<div class="section" id="section3">
... content ...
</div>
</div>
</div>
<ul class="nav">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
Using the following CSS (as an example for 3 600px divs floated next to each other inside a 1800px container, wrapped by a 600px viewport):
.viewport {
width: 600px;
overflow: hidden;
overflow-x: scroll;
}
.container {
width: 1800px;
}
.section {
float: left;
width: 600px;
}
For the clearfix class, refer to Bootstrap's clearfix.
Because you are scrolling horizontally, I think the <a name=...></a> things won't work, so I'd do an onload check for the hash, and scroll there when accessing the page with a preset hash. This has been done in the window load handler in the next snippet, together with starting in section 3 when there is no hash specified:
As for starting in section 3 on load, have this in your $(window).load() handler, for example:
$(window).load(function() {
var startSection = window.location.hash;
if (startSection == "") startSection = '#section3';
$('.viewport').scrollLeft($(startSection).offset().left);
window.location.hash = startSection;
});
Disclaimer: untested code! :) But please try these, and it should get you pretty close to what you are trying to achieve.
Hope this helps!
Why don't you scroll to that div on window load? And change bind with on, as of jQuery 1.7 .on() is the preferred method for attaching event handlers to a document
So your code should be something like this
$(document).ready( function(){
$('ul.nav a ').on('click ', function (event) {
var $anchor = $(this);
$('html, body ').stop().animate({
scrollLeft: $($anchor.attr('href')).offset().left
}, 1500, 'easeInOutExpo ');
event.preventDefault();
});
});
$(window).on('load', function () {
$('html, body').stop().animate({
scrollLeft: $('#section3').offset().left
}, 1500, 'easeInOutExpo ');
});

Set parent div height to content that is not overflowing

I have a slider that's in place on my website.
The basic way that it works is depicted in this jsfiddle -
http://jsfiddle.net/6h7q9/15/
I've written code to set the parent's height to the height of the content div. This worked fine, until I introduced some content that did not have a fixed height and whose height might increase while it was being shown on the page. Is there a way, I can dynamically change the height of this parent div whenever content inside it increases or decreases it's height.
HTML -
<div id="slider_container">
<div id="slider">
<div id="slide1">
Has content that might increase the height of the div....
</div>
<div id="slide2">
Has content that might increase the height of the div....
</div>
<div id="slide3">
Has content that might increase the height of the div....
</div>
</div>
</div>
<input type="button" value="Next" id="btnNext">
<input type="button" value="Previous" id="btnPrev">
<input type="button" value="Add text" id="btnAddText">
<div class="footer">
I appear after the largest container, irrespective of which one is present....
</div>
JavaScript -
var currSlider = 1;
$('#btnNext').click(function(){
debugger;
var margin = $('#slider').css('margin-left');
if(parseInt(margin) <= -400) {
return;
}
currSlider++;
// Moving the slider
$('#slider').css('margin-left', parseInt(margin) - 200 + 'px');
// Resetting the height...
$('#slider').height($('#slide' + currSlider).height());
});
$('#btnPrev').click(function(){
debugger;
var margin = $('#slider').css('margin-left');
if(parseInt(margin) >= 0) {
return;
}
currSlider--;
// Moving to the previous slider
$('#slider').css('margin-left', parseInt(margin) + 200 + 'px');
// Resetting the height...
$('#slider').height($('#slide' + currSlider).height());
});
$('#btnAddText').click(function() {
$('#slide' + currSlider).text('Hello World'.repeat(100));
});
String.prototype.repeat = function(times) {
return (new Array(times + 1)).join(this);
};
I hope this "answer" gets you going in the right direction. Since i don't have the time to fully look this up right now, i hope to send you in the right direction. if you do find out how to do this properly, please shoot me a message, since i would really like to know ^_^
http://www.w3.org/TR/DOM-Level-3-Events/#legacy-event-types
An example on how to use: (DOMSubtreeModified didn't work in IE from what i read. Therefor the propertchange event)
$('#slide1').on('DOMSubtreeModified propertychange', function() {
console.log('test',this);
});
Another option is by using the MutationObserver:
http://updates.html5rocks.com/2012/02/Detect-DOM-changes-with-Mutation-Observers
https://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html#mutation-observers
Updated 6-8-2014 15:00 CET
Since i totally misread the original post, this answer was useless to say the best. But since the problem is actually really easy to solve (or... at least i hope i understand the problem this time), i thought i'd post an answer that worked for the situation: a slider with content of different heights.
What was the problem with the original slider? You moved the content out of the container, which made it hidden. However, the container would still pick up the height of it, since it only had a fixed width. The fixed height on the '#slider' did not prevent the container of picking up the height from the '#slide-*'. Had you set the height for the container... all would be fine :-)
Here's the outline of the hidden slide, moved 'off canvas': http://i.gyazo.com/f2404e85263a7209907fdbc8f9d8e34e.png
I did not fix your fiddle by completing your code. I just rewrote it to provide you with an easier to maintain slider. Here's a fiddle with a working slider where you can add and remove stuff in the slides: http://jsfiddle.net/3JL2x/3/
Just remove the height properties in the .slide1, 2 and 3 and add min-height instead.
Like that :
#slider > div {
min-height:200px;
float:left;
width : 200px;
}
#slide1 {
background-color : red;
}
#slide2 {
background-color: green;
}
#slide3 {
background-color: blue;
}
Live example
http://jsfiddle.net/6h7q9/27/

jquery hide/show based on scroll

So I was given a web template that uses a jquery library called sticky, and it "sticks" the navigation (starts at the bottom and moves up) at the top of the page, as you scroll.
I want to be able to plop a logo onto the navigation once it hits its resting place (post scroll). Similar to this website - http://99u.com/. Once you scroll past the image header, the logo fade's in to the nav bar and then stays on the page. Anyhow, here is the excerpt of the jquery code:
<script>
$(window).load(function() {
$('nav').sticky({ topSpacing:0, className: 'sticky', wrapperClassName: 'my-wrapper' });
});
</script>
And here is the excerpt of the html:
<div with image slideshow></div>
<nav>
<div class="container">
<div class="thirteen columns">
<ul id="nav" class="links">
<li id="sticker"><img src="[image i want to display after scroll]" /></li>
<li>About</li>
<li>Contests</li>
<li>etc.</li>
</ul>
</div>
</div>
</nav>
<div's and the rest of the page's content></div>
This whole template is responsive. Any help would be appreciated, or if someone can point me in the right direction. Thanks!
Take a look at scrollTop and offset.
This is untested but it would look something like this:
$(window).scroll(function(){
if($("#nav").offset().top <= $(window).scrollTop)
$("#nav").css({"position":"fixed","top":"0px", "left":"0px"});
else
$("#nav").css({"position":"relative"});
});
Basically, as the user scrolls, check the windows scroll position and if it passes the top of the nav, switch the nav over to fixed positioning. In my code above, the check on the way back may need a little tweaking but when they scroll to a position less than the height of the nav, put the nav back to relative positioning.
Also instead of switching to position fixed you could show/hide a totally separate nav, might actually make life easier.
-Ken
You can test the position property of the menu and when it changes, hide/show the image via adding/removing a class:
CSS:
#sticker.hidden { width:0; height:0; border:0; padding:0; margin:0; }
#sticker.hidden * { display:none; }
Javascript:
$(window).load(function () {
$('nav').sticky({
topSpacing: 0,
className: 'sticky',
wrapperClassName: 'my-wrapper'
});
var elem = $('#sticker');
var nav = $('nav');
var pos = nav.css('position');
$(window).scroll(function(){
if (nav.css('position')!=pos) { // if changed
if (pos=='fixed') {
elem.addClass('hidden');
} else {
elem.removeClass('hidden');
}
pos = nav.css('position');
}
});
});
jsfiddle
Thanks for the suggestions. They both helped! Here is what i ended up doing:
<script>
$(window).load(function() {
$('#sticker').css({'display':'none'});
$('nav').sticky({ topSpacing:0, className: 'sticky', wrapperClassName: 'my-wrapper' });
$(this).scroll(function() {
if($('nav').offset().top <= $(window).scrollTop()) {
$('#sticker').fadeIn('fast');
} else {
$('#sticker').css({'display':'none'});
}
});
});
</script>

Categories

Resources