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

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

Related

How to scroll on click of a button to a certain element/div on the bottom of the page with jQuery?

I have tried different variations of this and it still does not work for me. I am trying to add an animation so that when I click in the button, it scrolls down to the certain element on the page.
Here's my code:
<script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<!-- jQuery code to show the working of this method -->
<script>
$(document).ready(function() {
$("#nav-projects").click(function() {
$("html, body").animate({
scrollTop: $(
'html, body').get(0).scrollHeight
}, 2000);
});
});
</script>
An alternative way with CSS without jQuery ($('#yourelement').offset().top;) or Javascript would be:
html {
scroll-behavior: smooth;
}
Goto A
Goto B
Goto C
<hr>
<div id="A" style="height:500px;">Section A</div>
<div id="B" style="height:500px;">Section B</div>
<div id="C" style="height:500px;">Section C</div>
Try this:
<script>
$(document).ready(function() {
$("#nav-projects").click(function() {
$("html, body").animate({
scrollTop: $(
#id).height()
}, 2000);
});
});
</script>
Replace id with the id of the element to which you wish to scroll to and adjust the height accordingly.

Scroll to top of an element without using animate

HOw can I scroll to top of an element without using animate()? I googled, but all answers are with animate().
$("#button").click(function() {
$('html, body').animate({
scrollTop: $("#elementtoScrollToID").offset().top
}, 2000);
});
I just want to instantly go to the top of an element. In my case, the animate() is not necessary.
Use .scrollTop()
$("#button").click(function() {
$('html, body').scrollTop( $("#elementtoScrollToID").offset().top);
});
.dummy {
height: 1200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="button">Test</button>
<div class="dummy"></div>
<div id="elementtoScrollToID">elementtoScrollToID</div>
You can do it just passing an anchor, pure HTML:
go to top
and you just add an <a name="top"></a> on the top of your website :)
You achieve the same affect without jQuery by using Window.scroll()
document.getElementById("button").onclick = function() {
window.scroll(0,document.getElementById("elementtoScrollToID").offsetTop);
};
<button id="button">Button</button>
<div id="elementtoScrollToID" style="margin: 800px 0;">
Scroll to here...
</div>
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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 ');
});

How to scroll to specific item using jQuery?

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(){
});
}

Categories

Resources