I am trying to get scrolling right on div tags by clicking on list of anchor tags using jquery.
enter code here
function scrollThere(targetElement, speed) {
// initiate an animation to a certain page element:
$('html, body , #side').stop().animate(
{ scrollTop: targetElement.offset().top }, // move window so target
element is at top of window
speed, // speed in milliseconds
'swing' // easing
); // end animate
} // end scrollThere function definition
//--- START NAV-ITEM CLICK EVENTS ---//
// when the user clicks a nav item:
$("#leftSidebar ul li a").click(function (e) {
e.preventDefault(); // don't jump like a typical html anchor
// find the index of the "#" character in the href string...
var startOfName = $(this).attr('href').indexOf("#"),
// ...then use it as the argument in the slice() method (add 1 so you
don't include the # character).
clickRef = $(this).attr('href').slice(startOfName + 1),
targetEl = $('a[name=' + clickRef + ']'); // select the element this
link is pointing to
// scroll there smoothly:
scrollThere(targetEl, 400);
});
The problem is that when I click on a link twice,it takes me to the top of the page and the scrolling messes up too.The scrolling for some reason dosent work properly as the size of div tags increase.Here is a fiddle https://jsfiddle.net/60tp46y3/18/ showing the problem.Ideally on clicking respective links on left the right section should scroll to the appropriate id.
Just adapted your code. It's working now.
https://jsfiddle.net/t0of2kzp/
The error was, that you didn't checked the current scroll position of the container, which contains all other elements.
// targetElement is the div surrounding the target a tag.
var postionOfTargetElement = targetElement.offset().top;
// That's the main container
var scrollPosition = targetElement.parent().scrollTop();
// Here we calculate the real top position with respecting the main containers scroll position.
var topTarget = postionOfTargetElement + scrollPosition;
Related
Here is the fiddle link https://jsfiddle.net/hitech0101/5vhdm5hy/
$('.block').click( function () {
$('#mainContainer').animate({'width':'20%'}, 1000);
$(this).css({'background-color':'blue'});
$('.block').css({'display':'block','width':'100%'});
$('.second').css({'display':'inline-block'})
});
In the fiddle, i am using jquery to convert the horizontal blocks into vertical blocks. I have changed the block color from red to blue when the block is clicked. When i click a particular block i would the scroll to move to the location of the block in the vertical view. I have tried jquery's scrollTop() method but still could not get it working the way i wanted it to. Please help.
The fiddle is partial representation of the webpage i am working on. There is more content on the original page which i have excluded. The maincontainer is the second container on the page.
No JavaScript necessary. You can specify an element in an anchor's href and it'll scroll it to the top of the window, including itself.
Wrap the div in an anchor or just use the anchor tag itself, they're both wrappers.
<a href="#scrollToMe">
<div id="scrollToMe"></div>
</a>
Just remember that it can only scroll the element into view to the best of its ability, if the item is at the bottom of the parent element the scroll will hit the bottom and it won't be able to go any further.
$(this).get(0).scrollIntoView();
Add this line into the .click function.
Fiddle
I suggest you get the offset top value and animate the #maincontainer to that position
$('.block').click( function () {
$('#mainContainer').animate({'width':'20%'}, 1000);
$(this).css({'background-color':'blue'});
$('.block').css({'display':'block','width':'100%'});
$('.second').css({'display':'inline-block'});
/*below is what i was talking about*/
var pos = $(this).offset();
$('#mainContainer').animate({ scrollTop: pos.top });
});
$(document).on("click", ".block", function() {
var _body_html = $('html, body');
var _scroll_to = $('.scroll-to');
var _top = _scroll_to.offset().top;
_body_html.animate({
scrollTop: _top
}, 1000);
setTimeout(function() {
_body_html.finish();
}, 1000);
});
I replaced the scrolling animation of my one page website with another scrolling animation which changes the URLs when you use the topbar (it was build in foundation)
While the URLs now change when I click an item in the topbar all the other links or clickable elements on my page make it scroll back to the top of the page.
For example when I try to click the next/prev buttons of my slider it scrolls back to the top of the page as if I clicked on Home.
Can someone see whats wrong with the code for the animation?
$(document).ready(function () {
$('a[href^="#"]').click(function () {
var target = $(this.hash),
hash = this.hash;
if (target.length == 0) {
target = $('a[name="' + this.hash.substr(1) + '"]');
}
if (target.length == 0) {
target = $('html');
}
$('html, body').animate({
scrollTop: target.offset().top
}, 500, function () {
location.hash = hash;
});
return false;
});
});
PS: When I scroll manually the URLs don't change when I go down to the next page. If anyone has a fix for this I'll be happy to here from you! (I tried using history.js but that only seems to work if you have a server, which I don't)
//* EDIT *//
I just found out it's not all links that make it scroll to the top of the page, just the buttons of my orbit slider and the menu button when the topbar is collapsed
//EDIT 2//
The URL now changes when I scroll to the next page!
The only problem I am seeing right now is that the buttons of my orbit slider and the menu button of the collapsed topbar act the same as my home button (makes the page scroll all the way back to the top) for some reason.
So the last thing I need to do is get the buttons working again. Making the menu button expand the topbar and making the next and prev buttons of my slider work as normal
If you only want to change the hash depending on the scrollPosition you are half way there.
You'll need to bind some logic to the scroll event. Here is a fork of your Fiddle where the hash is changed on scroll.
When the user scrolls the page we iterate through all .page elements and compare their offset().top against $( document ).scrollTop().
We set the new hash to be the id of the last .page element that has a lower offset().top than $( document ).scrollTop() is.
(I also debounced the function so it doesn't fire constantly when scrolling - you could of course remove that part)
You should however consider that by changing the hash you will jump to the equivalent element. Here is a guide on how to suppress that behaviour.
EDIT:
Here is an updated Fiddle where I implemented the solution from above for suppressing forced scroll on hash change.
I have three sections on my page, from top to bottom, A, B and C. You click on a button in section C. Now, some content is loaded in section A (above the button you clicked on), e.g. the content uses jQuery's slideDown() method.
Now, section C scrolls a little bit down (because the new content is making it do so). That's what I'd like to prevent. Is there a way that the browser automatically scrolls page to be at the exact same position as before the content loaded?
If you want to make sure that the button does not move on the screen at all, even though content is added above it, this should do it:
$("mybutton").click(function() {
//Save the vertical position of the button before content is added.
var x1 = $(this).offset().top;
//Do whatever the button is suppose to do, including adding the new content.
doAllTheStuff();
//See how much we moved.
var x2 = $(this).offset().top;
var dx = x2 - x1;
//Scroll the same amount to keep the button from moving on the screen.
$(document).scrollTop($(document).scrollTop() + dx);
});
If you are using this functionallity a lot on your page, you might want to wrap up the code a bit nicer. Here is a working JSFiddle.
This might also be interesting reading:
http://kirbysayshi.com/2013/08/19/maintaining-scroll-position-knockoutjs-list.html
Maintain page position while page length changes
jquery - keep window from changing scroll position while prepending items to a list?
You can scroll page to element when click on your button (probably your element).
$('html, body').animate({ scrollTop: $("#element").offset().top }, 2000);
Here an example: https://jsfiddle.net/kmser1uh/
UPDATE
A trick for scroll in the same exactly position is to save the offset of the element in the page after the scroll, and animate the scroll after button click.
The updated example:
https://jsfiddle.net/kmser1uh/2/
This is the save part:
var el;
var elPos;
var clr;
$(window).scroll(function(){
clearTimeout(clr);
clr = setTimeout(function(){
$('.fullWidthBodyElement').each(function(){
if ($(window).scrollTop() > $(this).offset().top &&
$(window).scrollTop() < $(this).offset().top + $(this).height()) {
el = this;
elPos = $(window).scrollTop() - $(this).offset().top;
}
});
},500);
});
And this the resume position:
$('html, body').animate({ scrollTop: ($(el).offset().top + elPos) }, 2000);
You Migt be using # in href attribute in anchor tag usejavascript:void(0);then you page will not get scrolled.
Want to implement infinite scroll based on mouse scrol when it reaches the specified container bottom. I came to this plugin after searching http://www.infinite-scroll.com/ which needs the following basic requirements:
// infinitescroll() is called on the element that surrounds
// the items you will be loading more of
$('#content').infinitescroll({
navSelector : "div.navigation",
// selector for the paged navigation (it will be hidden)
nextSelector : "div.navigation a:first",
// selector for the NEXT link (to page 2)
itemSelector : "#content div.post"
// selector for all items you'll retrieve
});
i.e next and previous selectors. Can we have infinite scroll based on mouse scroll instead of clicking next, prev links i.e when mouse reaches the specified container bottom load the content via ajax
Add a function to the scroll event and check if you scrolled down to the bottom.
you have to adjust numbers and tweak the code a bit according to your layout:
var $window = $(window);
$(document).ready(function () {
$(window).scroll(function () {
var scrollheight2;
scrollheight2 = $window.scrollTop();
if (($("#content").height() - scrollheight2) <= 100) {
//AJAX STUFF
}
});
});
I got the following HTML:
<div style="height:200px;overflow-y:scroll;">
<table>.....</table>
</div>
With this setup I'm somewhat mimicking the expanded <select> control with #size attribute defined. So, that a user could select a row in the table. Is there a way, to make the table "jump up", so that the selected row appears to be at the top of the div and the vertical scrollbar scrolled to its position. I don't need the actual scrolling effect. The table should change it's position right away on row click.
This might work:
$("#scrollableDiv").animate({
scrollTop: 200 // scrolls to the bottom
}, 1000);
I suggest using scrollTop (or even animate it if you want).
$('div')[0].scrollTop = 200 //would set the scrollable div to 200px down.
http://jsfiddle.net/8mepH/
Here is an modified extract of the code used in:
http://www.balupton.com/sandbox/jquery-scrollto/demo/
To do what you want:
// Fetch the scrollable div
$container = $('#scrollable');
// Fetch the target div
$target = $('#target');
// Prepare the Inline Element of the Container
var $inline = $('<span/>').css({
'position': 'absolute',
'top': '0px',
'left': '0px'
});
var position = $container.css('position');
// Insert the Inline Element of the Container
$container.css('position','relative');
$inline.appendTo($container);
// Determine the Offsets
var startOffset = $inline.offset().top,
targetOffset = $target.offset().top,
offsetDifference = targetOffset - startOffset;
// Perform the jump
$container.css('scrollTop',offsetDifference+'px')
We add a inline here to ensure we get the correct start position within the scrollable area. We use a offset difference so if you want to do animations it animations from the start position, rather than jumping somewhere else.