Scroll to a div using jQuery

JqueryScroll

Jquery Problem Overview


so I have a page that has a fixed link bar on the side. I'd like to scroll to the different divs. Basically the page is just one long website, where I'd like to scroll to different divs using the menu box to the side.

Here is the jQuery I have so far

$(document).ready(function() {
    $('#contactlink').click = function() {
        $(document).scrollTo('#contact');
    }
});

The issue is it is automatically going to the contact div when it loads, then when I press the #contactlink in the menu it scrolls back to the top.

EDIT: HTML

<!DOCTYPE html>

<html lang="en">

	<head>
	<meta charset="utf-8">
	
	<!-- jQuery-->
	<script src = "<?php echo base_url() ?>assets/js/jquery.js"></script>
	
	<!-- .js file-->
	<script src = "<?php echo base_url() ?>assets/js/pagetwo.js"></script>

	<link rel="stylesheet" type="text/css" href="<?php echo base_url()?>assets/css/reset.css" />	
			
	<!-- .css for page -->
	<link rel="stylesheet" type="text/css" href="<?php echo base_url()?>assets/css/pagetwo.css"/>						
	
	<!-- page title-->
	<title><!-- Insert Title --></title>
	

</head>
<body>
	<div id="container">
	
		<div id="sidebar">
			<ul>
				<li><a id = "aboutlink" href="#">auck</a></li>
				<li><a id = "peojectslink" href="#">Projects</a></li>
				<li><a id = "resumelink" href="#">Resume</a></li>
				<li><a id = "contactlink" href="#">Contact</a></li>
			</ul>
		</div>
		
		<div id="content">
			<div class="" id="about">
				<p class="header">uck</p>
				<p class="info">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
			</div>
			<div class="sections"id="projects">
				<p class = "header">Projects</p>
				<p class="info">Projects</p>
			</div>
			<div class="sections" id="resume">
				<p class = "header">Resume</p>
				<p class="info">Resume</p>
			</div>
			<div class="sections" id="contacts">
				<p class = "header">Contact</p>
				<p class="info">Contact</p>
			</div>
		</div>
	</div>
</body>

Jquery Solutions


Solution 1 - Jquery

First, your code does not contain a contact div, it has a contacts div!

In sidebar you have contact in the div at the bottom of the page you have contacts. I removed the final s for the code sample. (you also misspelled the projectslink id in the sidebar).

Second, take a look at some of the examples for click on the jQuery reference page. You have to use click like, object.click( function() { // Your code here } ); in order to bind a click event handler to the object.... Like in my example below. As an aside, you can also just trigger a click on an object by using it without arguments, like object.click().

Third, scrollTo is a plugin in jQuery. I don't know if you have the plugin installed. You can't use scrollTo() without the plugin. In this case, the functionality you desire is only 2 lines of code, so I see no reason to use the plugin.

Ok, now on to a solution.

The code below will scroll to the correct div if you click a link in the sidebar. The window does have to be big enough to allow scrolling:

// This is a functions that scrolls to #{blah}link
function goToByScroll(id) {
    // Remove "link" from the ID
    id = id.replace("link", "");
    // Scroll
    $('html,body').animate({
        scrollTop: $("#" + id).offset().top
    }, 'slow');
}

$("#sidebar > ul > li > a").click(function(e) {
    // Prevent a page reload when a link is pressed
    e.preventDefault();
    // Call the scroll function
    goToByScroll(this.id);
});

Live Example

( Scroll to function taken from here )


PS: Obviously you should have a compelling reason to go this route instead of using anchor tags <a href="#gohere">blah</a> ... <a name="gohere">blah title</a>

Solution 2 - Jquery

There is no .scrollTo() method in jQuery, but there is a .scrollTop() one. .scrollTop expects a parameter, that is, the pixel value where the scrollbar should scroll to.

Example:

$(window).scrollTop(200);

will scroll the window (if there is enough content in it).

So you can get this desired value with .offset() or .position().

Example:

$(window).scrollTop($('#contact').offset().top);

This should scroll the #contact element into view.

The non-jQuery alternate method is .scrollIntoView(). You can call that method on any DOM element like:

$('#contact')[0].scrollIntoView(true);

true indicates that the element is positioned at the top whereas false would place it on the bottom of the view. The nice thing with the jQuery method is, you can even use it with fx functions like .animate(). So you might smooth scroll something.

Reference: .scrollTop(), .position(), .offset()

Solution 3 - Jquery

you can try :

$("#MediaPlayer").ready(function(){
    $("html, body").delay(2000).animate({
        scrollTop: $('#MediaPlayer').offset().top 
    }, 2000);
});

Solution 4 - Jquery

Add this little function and use it as so: $('div').scrollTo(500);

jQuery.fn.extend(
{
  scrollTo : function(speed, easing)
  {
    return this.each(function()
    {
      var targetOffset = $(this).offset().top;
      $('html,body').animate({scrollTop: targetOffset}, speed, easing);
    });
  }
});

Solution 5 - Jquery

OK guys, this is a small solution, but it works fine.

suppose the following code:

<div id='the_div_holder' style='height: 400px; overflow-y: scroll'>
  <div class='post'>1st post</div>
  <div class='post'>2nd post</div>
  <div class='post'>3rd post</div>
</div>

you want when a new post is added to 'the_div_holder' then it scrolls its inner content (the div's .post) to the last one like a chat. So, do the following whenever a new .post is added to the main div holder:

var scroll = function(div) {
    var totalHeight = 0;
    div.find('.post').each(function(){
       totalHeight += $(this).outerHeight();
    });
    div.scrollTop(totalHeight);
  }
  // call it:
  scroll($('#the_div_holder'));

Solution 6 - Jquery

First get the position of the div element upto which u want to scroll by jQuery position() method.
Example : var pos = $("div").position();
Then get the y cordinates (height) of that element with ".top" method.
Example : pos.top;
Then get the x cordinates of the that div element with ".left" method.
These methods are originated from CSS positioning.
Once we get x & y cordinates, then we can use javascript's scrollTo(); method.
This method scrolls the document upto specific height & width.
It takes two parameters as x & y cordinates. Syntax : window.scrollTo(x,y);
Then just pass the x & y cordinates of the DIV element in the scrollTo() function.
Refer the example below ↓ ↓

<!DOCTYPE HTML>
    <html>
    <head>
        <title>
            Scroll upto Div with jQuery.
        </title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
        <script>
            $(document).ready(function () {
                $("#button1").click(function () {
                    var x = $("#element").position(); //gets the position of the div element...
                    window.scrollTo(x.left, x.top); //window.scrollTo() scrolls the page upto certain position....
                    //it takes 2 parameters : (x axis cordinate, y axis cordinate);
                });
            });
            </script>
    </head>
    <body>
        <button id="button1">
            Click here to scroll
        </button>
        
        <div id="element" style="position:absolute;top:200%;left:0%;background-color:orange;height:100px;width:200px;">
            The DIV element.
            </div>
        </body>
    </html>

Solution 7 - Jquery

No need too these. Just simply add div id to href of a < a > tag

<li><a id = "aboutlink" href="#about">auck</a></li>

Just like that.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontshauckView Question on Stackoverflow
Solution 1 - JqueryPeter AjtaiView Answer on Stackoverflow
Solution 2 - JqueryjAndyView Answer on Stackoverflow
Solution 3 - JqueryIT VlogsView Answer on Stackoverflow
Solution 4 - JqueryRyanView Answer on Stackoverflow
Solution 5 - JquerychristianView Answer on Stackoverflow
Solution 6 - JquerySayyed SalmanView Answer on Stackoverflow
Solution 7 - JqueryArmin AkhlaghView Answer on Stackoverflow