Previous and Next Scrolling to next post - javascript

I've been struggling with this all day.. I've got a couple of posts, each have a next and previous button. The idea is for each post and its next and previous buttons, to scroll the window to the next post or previous post. I have tried using the each() function and unfortunately, its tricky to get working.
This is the jQuery so far:
var scrollTo = function(element) {
$('html, body').animate({
scrollTop: element.offset().top
}, 100);
}
function prev_next_scrolling() {
var articles = $("article.post"),
counter = 0;
articles.each( function() {
var articles = $(this);
$('.next-btn', articles).click( function() {
scrollTo($('article.post').eq(counter + 1));
});
$('.prev-btn', articles).click( function() {
scrollTo($('article.post').eq(counter - 1));
});
counter++;
});
}
prev_next_scrolling();
And this is the HTML:
<article class="post">
<h2>Post Title</h2>
<p>Post description</p>
Previous
Next
</article>
Here is the jsfiddle link for you guys to have a looksie!
http://jsfiddle.net/casacoda/2zM3Q/
Any help will be much appreciated! Thanks in advance guys!

The problem with your code is that counter is defined in the scope of prev_next_scrolling(), so all the functions run by the each() method will use the very same instance of the variable. Each time you increase counter, that will happen for all places where it has been used.
You can fix that by introducing a variable local to the function that handles a specific element -- or actually, you don't have to because jQuery already gives you exacly that as an optional parameter in the each() callable. See http://api.jquery.com/each/
So here's the correct code (http://jsfiddle.net/2zM3Q/3/):
var scrollTo = function(element) {
$('html, body').animate({
scrollTop: element.offset().top
}, 100);
}
function prev_next_scrolling() {
var articles = $("article.post"),
counter = 0;
articles.each( function(index) {
var articles = $(this);
$('.next-btn', articles).click( function() {
scrollTo($('article.post').eq(index + 1));
});
$('.prev-btn', articles).click( function() {
scrollTo($('article.post').eq(index - 1));
});
counter++;
});
}
prev_next_scrolling();
There are still some problems: It doesn't check whether it already is the first/last post and if it's already at the end of the page it obviously won't scroll any further, creating the illusion of a "broken" link (because nothing seems to be happening after clicking it.)

I've updated the fiddle to address all your concerns in the comments
Updated Working Fiddle
I got it working without all your each code, just navigating the dom.
Let me know if you have questions about the Fiddle provided. Basically this takes advantage of your current structure being known, it finds the next ARTICLE using parent().next() and then finds that ARTICLEs h2. It then uses the H2s vertical offset position to scroll to it. Same for previous links but using parent().prev()
$(document).on('click', '.next-btn', function(){
// find the next anchor
var nextAnchor = $(this).closest('article').next().find('h2')
$('html,body').animate({scrollTop: nextAnchor.offset().top},'slow');
});
$(document).on('click', '.prev-btn', function(){
// find the previous anchor
var prevAnchor = $(this).closest('article').prev().find('h2')
$('html,body').animate({scrollTop: prevAnchor.offset().top},'slow');
});
One thing to note, if the H2 in question is already visible on the screen it will not scroll UP to anything, only if its off screen will it scroll UP to it. Scroll down will always move the screen if needed.

Related

Update scroll position on resize of window

I'm currently using a combination of smooth scroll and IDs/anchor tags to scroll to content on my site. The code below is getting the ID of the next 'section' in the DOM, and adding it's ID as the 'view next section' href, so once it's clicked, it'll scroll to the top of that div. Then, it iterates through, updating the href with the next ID each time etc until the last section is seen and it scrolls back to the top. Pretty straightforward.
The only problem is that the 'sections' are fullscreen images, so as it's scrolling to the top of the next section, if you resize the browser, the top position of that section (where we scrolled to) has moved, and means the position is lost.
I've created a JSFiddle. You can see this happening after you click the arrow to visit the next section then resize the window: http://jsfiddle.net/WFQ9t/3/
I'm wanting to keep this top position fixed at all times so even if you resize the browser, the scroll position is updated to reflect this.
Thanks in advance,
R
var firstSectionID = $('body .each-section').eq(1).attr('id');
$('.next-section').attr('href', '#' + firstSectionID);
var i = 1;
$('.next-section').click(function() {
var nextSectionID = $('body .each-section').eq(i).attr('id');
i++;
$('.next-section').attr('href', '#' + nextSectionID);
var numberOfSections = $('body .each-section').length;
var lastSectionID = $('body .each-section').eq(numberOfSections).attr('id');
if ($('.next-section').attr('href') == '#' + lastSectionID ) {
$('.next-section').attr('href', '#introduction');
i = 1;
}
});
Ok, Please check out this fiddle: http://jsfiddle.net/WFQ9t/9/
The few things I did were:
Made some global variables to handle the screen number (which screen you're on and also the initial window height. You will use this when the screen loads and also when you click on the .next-session arrow.
var initWinHeight = $(window).height();
var numSection = 0;
Then I tossed those variables into your resizeContent() function
resizeContent(initWinHeight, numSection)
so that it will work on load and resize
I made the body move around where it needs to, to accomodate for the movement of the divs (I still don't understand what divs are moving when the regular animation happens).
$('body').css({
top: (((windowHeight - initWinHeight)*numSection)*-1) + "px"
});
Then in your click function, I add 1 to the section number, reset the initial window height and then also reset the body to top:0. The normal animation you have already puts the next section at the top of the page.
numSection++;
initWinHeight = $(window).height();
$('body').css({top:"0px"}, 1000);
Finally, I reset the numSections counter when you reach the last page (You might have to make this 0 instead of 1)
numSection = 0;
The fiddle has all of this in the correct places, these are just the steps I took to change the code.
Here is a solution that i found, but I dont use anchor links at this point, i use classes
Here is my HTML code:
<section class="section">
Section 1
</section>
<section class="section">
Section 2
</section>
<section class="section">
Section 3
</section>
<section class="section">
Section 4
</section>
And here is my jQuery/Javascript code,
I actually used a preety simple way:
$('.section').first().addClass('active');
/* handle the mousewheel event together with
DOMMouseScroll to work on cross browser */
$(document).on('mousewheel DOMMouseScroll', function (e) {
e.preventDefault();//prevent the default mousewheel scrolling
var active = $('.section.active');
//get the delta to determine the mousewheel scrol UP and DOWN
var delta = e.originalEvent.detail < 0 || e.originalEvent.wheelDelta > 0 ? 1 : -1;
//if the delta value is negative, the user is scrolling down
if (delta < 0) {
next = active.next();
//check if the next section exist and animate the anchoring
if (next.hasClass('section')) {
var timer = setTimeout(function () {
$('body, html').animate({
scrollTop: next.offset().top
}, 800);
next.addClass('active')
.siblings().removeClass('active');
clearTimeout(timer);
}, 200);
}
} else {
prev = active.prev();
if (prev.length) {
var timer = setTimeout(function () {
$('body, html').animate({
scrollTop: prev.offset().top
}, 800);
prev.addClass('active')
.siblings().removeClass('active');
clearTimeout(timer);
}, 200);
}
}
});
/*THE SIMPLE SOLUTION*/
$(window).resize(function(){
var active = $('.section.active')
$('body, html').animate({
scrollTop: active.offset().top
}, 10);
});

Scrolling to Div IDs with Jquery

Due to css properties my scrolling to div tags has too much margin-top. So I see jquery as the best solution to get this fixed.
I'm not sure why this isn't working, I'm very new to Js and Jquery. Any help us greatly appreciated.
Here is a quick look at Js. I found that when your div ids are in containers to change the ('html, body') to ('container)
Here is my jsfiddle
jQuery(document).ready(function($){
var prevScrollTop = 0;
var $scrollDiv = jQuery('div#container');
var $currentDiv = $scrollDiv.children('div:first-child');
var $sectionid = 1;
var $numsections = 5;
$scrollDiv.scroll(function(eventObj)
{
var curScrollTop = $scrollDiv.scrollTop();
if (prevScrollTop < curScrollTop)
{
// Scrolling down:
if ($sectionid+1 > $numsections) {
console.log("End Panel Reached");
}
else {
$currentDiv = $currentDiv.next().scrollTo();
console.log("down");
console.log($currentDiv);
$sectionid=$sectionid+1;
console.log($currentDiv.attr('id'));
var divid =$currentDiv.attr('id');
jQuery('#container').animate({scrollTop:jQuery('#'+divid).position().top}, 'slow');
}
}
else if (prevScrollTop > curScrollTop)
{
// Scrolling up:
if ($sectionid-1 == 0) {
console.log("Top Panel Reached");
}
else {
$currentDiv = $currentDiv.prev().scrollTo();
console.log("up");
console.log($currentDiv);
$sectionid=$sectionid-1;
var divid =$currentDiv.attr('id');
jQuery('html, body').animate({scrollTop:jQuery('#'+divid).position().top}, 'slow');
}
}
prevScrollTop = curScrollTop;
});
});
I'm not entirely sure what you want but scrolling to a <div> with jQuery is simpler than your code.
For example this code replaces the automatic jumping behaviour of anchors with smoother scrolling:
$(document).ready(function(e){
$('.side-nav').on('click', 'a', function (e) {
var $this = $(this);
var top = $($this.attr('href')).offset().top;
$('html, body').stop().animate({
scrollTop: top
}, 'slow');
e.preventDefault();
});
});
You can of course adjust the top variable by adding or removing from it like:
var top = $($this.attr('href')).offset().top - 10;
I have also made a fiddle from it (on top of your HTML): http://jsfiddle.net/Qn5hG/8/
If this doesn't help you or your question is something different, please clarify it!
EDIT:
Problems with your fiddle:
jQuery is not referenced
You don't need jQuery(document).ready() if the jQuery framework is selected with "onLoad". Remove the first and last line of your JavaScript.
There is no div#container in your HTML so it's no reason to check where it is scrolled. And the scroll event will never fire on it.
Your HTML is invalid. There are a lot of unclosed elements and random tags at the end. Make sure it's valid.
It's very hard to figure out what your fiddle is supposed to do.

Slide HTML Table rows up and repeate

I found some cool code while working on a project. Its jquery that effects a html table. It basically makes the tbody scroll up so the row that was at the top goes to the bottom and the rest of the rows shift up. This is what I mean:
<tr><td>1a</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td></tr>
<tr><td>1b</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td></tr>
<tr><td>1c</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td></tr>
<tr><td>1d</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td></tr>
becomes:
<tr><td>1b</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td></tr>
<tr><td>1c</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td></tr>
<tr><td>1d</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td></tr>
<tr><td>1a</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td></tr>
Row 1a moves to the bottom. This is the jquery code I am using:
<script type="text/javascript">
$.fn.infiniteScrollUp=function(){
var self=this,kids=self.children()
kids.slice(20).hide()
setInterval(function(){
kids.filter(':hidden').eq(0).fadeIn()
kids.eq(0).fadeOut(function(){
$(this).appendTo(self)
kids=self.children()
})
},5000)
return this
}
$(function(){
$('tbody').infiniteScrollUp()
})
</script>
This works fine. No problems. How ever when I tried to make it so it just slides up, just like a reel of some sort, it either 1) stops adding it to the bottom, 2) stops removing them from the top, or 3) nothing. How can I change this effect to slide up?
Here is the jsfiddle example.
Sliding tr elements up/down is tricky. They don't behave like block elements.
This is the best I can manage :
$.fn.infiniteScrollUp = function() {
var self = this;
var kids = self.children();
kids.children('td, th').wrapInner('<div class="dummy"/>')
setInterval(function() {
var first = kids.eq(0),
clone = first.clone().appendTo(self);
first.find(".dummy").slideUp(1000, function() {
kids = kids.not(first).add(clone);
first.remove();
});
}, 2000);
return this;
};
Updated fiddle
I'm not sure about the plugin you have added above but here is another quick way around it that works as you have described, a little bit simpler in my opinion. There may be better ways around it.
function moveRows(){
firstTR = $('tbody tr').first();
firstTR.animate({opacity:0},
function(){$('tbody').append(firstTR);});
firstTR.animate({opacity:1});
}
setInterval(function(){
moveRows();
},1000);
And here is a Fiddle example.

Jquery - Carasol build finished and would like advice on best practice / neatening up my code

I have been building my own carasol over the past few days.
My Jquery is based on tutorials on the web and also from help and advice from SO.
I am not a Jquery guru just an enthusiast and think my code is a little sloppy, hence the post.
here is a link to the working code: http://jsfiddle.net/JHqBA/2/ (updated link)
basically what happens is:
if someone hits the page with a # values in the url it will show the appropriate slide and example would be www.hello.com#two, this would slide to slide two
if someone clicks the numbers it will show the appropriate slide
next and prev also slide through the slides.
The question is, is there anything i could have wrote better as i know there is alot of duplicate code.
I understand its a big ask but it would help me learn a little more (i think my code is a little old school)
if anyone has any questions please feel free to ask and ill answer what it does or is supposed to do.
Sluap
--- Edit ----
I have made only one aniamtion function now which has got rid of alot of duplicate code.
I have yet to look into on function but will do soon.
I would like to know more about the create a new function, outside of the jQuery ready block as i cant get this working or quite understand how i can get it to work sorry
any more tips would be great ill carry on working on this project till i am happy with it.
also is there a better way to write:
if ($slideNumber == 1) {
$('#prev').attr("class", "not_active")
$('#next').attr("class", "active")
}
else if ($slideNumber == divSum) {
$('#next').attr("class", "not_active");
$('#prev').attr("class", "active");
}
else {
$('#prev').attr("class", "active")
$('#next').attr("class", "active")
};
Jquery full:
$(document).ready(function () {
//////////////////////////// INITAL SET UP /////////////////////////////////////////////
//Get size of images, how many there are, then determin the size of the image reel.
var divWidth = $(".window").width();
var divSum = $(".slide").size();
var divReelWidth = divWidth * divSum;
//Adjust the image reel to its new size
$(".image_reel").css({ 'width': divReelWidth });
//set the initial not active state
$('#prev').attr("class", "not_active");
//////////////////////////// SLIDER /////////////////////////////////////////////
//Paging + Slider Function
rotate = function () {
var triggerID = $slideNumber - 1; //Get number of times to slide
var image_reelPosition = triggerID * divWidth; //Determines the distance the image reel needs to slide
//sets the active on the next and prev
if ($slideNumber == 1) {
$('#prev').attr("class", "not_active")
$('#next').attr("class", "active")
}
else if ($slideNumber == divSum) {
$('#next').attr("class", "not_active");
$('#prev').attr("class", "active");
}
else {
$('#prev').attr("class", "active")
$('#next').attr("class", "active")
};
//Slider Animation
$(".image_reel").animate({
left: -image_reelPosition
}, 500);
};
//////////////////////////// SLIDER CALLS /////////////////////////////////////////////
//click on numbers
$(".paging a").click(function () {
$active = $(this); //Activate the clicked paging
$slideNumber = $active.attr("rel");
rotate(); //Trigger rotation immediately
return false; //Prevent browser jump to link anchor
});
//click on next button
$('#next').click(function () {
if (!$(".image_reel").is(':animated')) { //prevent clicking if animating
var left_indent = parseInt($('.image_reel').css('left')) - divWidth;
var slideNumberOn = (left_indent / divWidth);
var slideNumber = ((slideNumberOn * -1) + 1);
$slideNumber = slideNumber;
if ($slideNumber <= divSum) { //do not animate if on last slide
rotate(); //Trigger rotation immediately
};
return false; //Prevent browser jump to link anchor
}
});
//click on prev button
$('#prev').click(function () {
if (!$(".image_reel").is(':animated')) { //prevent clicking if animating
var left_indent = parseInt($('.image_reel').css('left')) - divWidth;
var slideNumberOn = (left_indent / divWidth);
var slideNumber = ((slideNumberOn * -1) - 1);
$slideNumber = slideNumber;
if ($slideNumber >= 1) { //do not animate if on first slide
rotate(); //Trigger rotation immediately
};
}
return false; //Prevent browser jump to link anchor
});
//URL eg:www.hello.com#one
var hash = window.location.hash;
var map = {
one: 1,
two: 2,
three: 3,
four: 4
};
var hashValue = map[hash.substring(1)];
//animate if hashValue is not null
if (hashValue != null) {
$slideNumber = hashValue;
rotate(); //Trigger rotation immediately
return false; //Prevent browser jump to link anchor
};
});
Question and answer has been moved over to https://codereview.stackexchange.com/questions/8634/jquery-carasol-build-finished-and-would-like-advice-on-best-practice-neateni/8635#8635
1) Separation of Concerns
Start by refactorring your code in to more granular functions.
You can read more about SoF at http://en.wikipedia.org/wiki/Separation_of_concerns
Update:
E.g. Instead of having your reel resizing code inline, put it in it's own function, like this:
function setImageReelWidth () {
//Get size of images, how many there are, then determin the size of the image reel.
var divWidth = $(".window").width();
var divSum = $(".slide").size();
var divReelWidth = divWidth * divSum;
//Adjust the image reel to its new size
$(".image_reel").css({ 'width': divReelWidth });
}
This achieves 2 things:
a. First, it groups a block of code that is logically cohesive, removing it from the main code which results in a much cleaner code habitat.
b. It effectively gives a label to the code block via the function name that is descriptive of what it does, and therefore makes understanding of the code much simpler.
Later, you can also encapsulate the whole thing in it's own "class" (function) and you can move it into it's own js file.
2) The jQuery "on" function
Use the "on" function to attach your click events, rather than the "click" function.
http://api.jquery.com/on/
This has the added advantage of also binding it to future elements matching your selector, even though they do not exist yet.
3) The ready function
// I like the more succinct:
$(handler)
// Instead of:
$(document).ready(handler)
But you might like the more obvious syntax.
Those are just a few things to start with.
-- Update 1 --
Ok, StackOverflow is not really suited to a refactoring work in progress, but we'll make do. I think you should keep your original code block in your question, so that future readers can see where it started and how it systematically improved.
I would like to know more about the create a new function, outside of
the jQuery ready block as i cant get this working or quite understand
how i can get it to work sorry
I am not familiar with jsfiddle.net, but it looks cool and helpful, but might also be a bit confusing if you don't know what is going on. I am not sure I do :), but I think that script editor window results in a .js file that is automatically referenced by the html file.
So here is an example of a function defined outside of the ready block, but referenced from within.
function testFunction () {
alert ('it works');
}
$(document).ready(function () {
testFunction();
// ... other code
});
This should pop up an alert box that says, "it works" when the page is loaded.
You can try it for yourself.
Then, once you got that working, you can refactor other logically cohesive blocks of code into their own functions. Later you can wrap them all up into their own javascript 'class'. But we'll get to that.

Make overflow automatically go down every few seconds

I want that scroll would automatically go down a little bit every few seconds and that would expose more text. Is it possible to do that? By overflow I mean this: http://jsfiddle.net/Bnfkv/2/
You can use a timer that relaunches itself it there is anything left to do:
function scroll() {
$('#x').animate({ scrollTop: '+=5px' }, 100, function() {
if($('#x table').height() - this.scrollTop - $('#x').height() > 0)
setTimeout(scroll, 500);
});
}
scroll();
And an updated example: http://jsfiddle.net/ambiguous/2PpyJ/
Note that I added id="x" to your HTML to make it easier to reference the <div>.
var myElement = document.getElementById(.......); // or use jquery
var scrolling = setInterval(
function() {
//pick one:
//myElement.scrollBy(0,1); // if it's a textarea or something
//myElement.scrollTop = myElement.scrollTop+1; // if it's a DIV
},
10 // every 10ms
);
To stop it:
clearInterval(scrolling);

Categories