loop through div continuously w/ auto scroll - javascript

When a page loads with the div below I want the page to start auto scrolling and keep looping through the content over and over again. To see an example of what I am trying to achieve go here
<div id="contentwrapper">
<div class="post">some content</div>
<div class="post">some content</div>
<div class="post">some content</div>
<div class="post">some content</div>
<div class="post">some content</div>
<div class="post">some content</div>
</div>
Any help will be greatly appreciated as I have tried almost everything with no success.

You can change the scroll position of an element by setting the scrollTop property. To update it continuously, you could try:
var scrollDistancePerSecond = 50; // Scroll 50px every second.
var scrollDistancePerAnimationFrame = Math.ceil(scrollDistancePerSecond / 60); // Animate at 60 fps.
var wrapper = document.getElementById('contentwrapper');
autoScroll(wrapper);
function autoScroll(element){
if (element.scrollTop < element.scrollHeight)
window.requestAnimationFrame(autoScroll.bind(null,element));
element.scrollTop += scrollDistancePerAnimationFrame;
}
Live example here.
As for the continuous loop, you could wrap the .post elements in an inner wrapper (e.g., a <div id="inner-wrap">. Then you could duplicate the content by appending a clone of the inner-wrapped elements inside the outer wrapper.
var innerWrap = document.getElementById('inner-wrap');
var clone = document.createElement('div');
clone.innerHTML = innerWrap.innerHTML;
wrapper.append(clone);
Then, inside your animation function, you can check whether the wrapper's scrollTop has reached innerWrap.scrollHeight. If it has, you can jump back to the top! It'll take some fine-tuning to get a seamless effect.
Update
The linked page does not use scrollTop, but animates the y component of the CSS transform translate3d on the wrapper <div>. You might get more performant results using CSS transitions or animations over JavaScript. Here is an example in pure CSS3.

Related

Adding offset().top amount on scroll

I have a fixed piece of text and I'm trying to add a different class each time the text enters a div on scroll. I've got it working no problem. But if I add an offset amount to the fixed text e.g.
top: 400px
I need to counter this offset in the JS. But I can't seem to figure it out. I've tried using:
.offset().top 400);
But it's not working. Here's a code i'm currently using:
HTML
<p class="text">TEXT HERE</p>
<div class="section1"></div>
<div class="section2"></div>
<div class="section3"></div>
<div class="section4"></div>
JS
$(window).scroll(function (event) {
var scroll = $(window).scrollTop();
$('.text').toggleClass('blue',
scroll >= $('.section1').offset().top
);
$('.text').toggleClass('magenta',
scroll >= $('.section2').offset().top
);
$('.text').toggleClass('green',
scroll >= $('.section3').offset().top
);
$('.text').toggleClass('orange',
scroll >= $('.section4').offset().top
);
});
//trigger the scroll
$(window).scroll();//ensure if you're in current position when page is refreshed
The text needs to add class as soon as it enters the relevant div.
Here's a working fiddle: http://jsfiddle.net/6PrQW/334/
So you did most everything right, but I think where you went wrong is here: var scroll = $(window).scrollTop();
You don't want to calculate using the window offset, rather you want to use the offset of your sticky text. So instead use: var scroll = $('.text').offset().top;
Let me know if that helps.
edit,
and here is your fiddle with the edits.
Note that I edited your line for setting the blue class since you don't want to match the sticky offset against itself.
To find out when something is within your window, you've gotta use something like...
if($(elem).offset().top - $(window).scrollTop < $(window).height()){
//stuff
}
That should trigger as soon as elem is visible on the page! You can check it against $(window).height()/2, for example, if you want it to trigger in the center of the page instead. Hope this helps!

Splitting 'contenteditable' article into vertical pages with header and footer

I am working on a basic WYSIWYG word processor dealing with lengthy documents. Currently I am taking a HTML article element filled with approximately 5000 divs and applying some jQuery code to style and format it. 5000 is likely to be the absolute maximum.
Firstly, I use regex to apply CSS and this is working nicely at about
107ms.
Secondly, I iterate over the divs, storing their height and
every 1000px, inserting some HTML to act as a page break (the
pagination is vertical - imagine pages in MS Word). The second part
takes around 1200ms.
For initial page loading, I'm okay with that. Unfortunately, the article element needs to be contenteditable.
When a user changes the content of the article, I can simply apply my regex on the div they have changed (0-1ms) and that is no problem, however, any change to the content means (a possible) altering of the height between page breaks, and therefore necessitates repagination.
Having the browser lock up for a second every time the user hits return, delete, ends up on a new line or numerous other additional events that would alter the pagination is obviously not practical. While performance is better when making changes nearer the end of document, the user requires the same level of responsiveness when making changes to page one.
I need to address this performance issue and make the UI responsive when repaginating.
Here's an example of the HTML before the JS code is run on it:
<article contenteditable="true">
<header contenteditable="false"><h1>Header Text</h1></header>
<div>Content</div>
<div>Content</div>
<div>Content</div>
...
<footer contenteditable="false"><h3>Footer Text</h3></footer>
</article>
And after the JS code is run:
<article contenteditable="true">
<header contenteditable="false"><h1>Header Text</h1></header>
<div class="regex-set-class">Content</div>
<div class="regex-set-class">Content</div>
<div class="regex-set-class">Content</div>
<section contenteditable="false">
<h3>Footer Text</h3>
<figure><hr><hr></figure>
<h1>Header Text</h1>
<h2>Page Number</h2>
</section>
<div class="regex-set-class">Content</div>
<div class="regex-set-class">Content</div>
<div class="regex-set-class">Content</div>
...
<footer contenteditable="false"><h3>Footer Text</h3></footer>
</article>
And here is the JS code performing the pagination:
function PaginateDocument()
{
// Variables
var height = 0;
var page_count = 1;
// Remove existing page breaks
$("section").remove();
// Iterate over each div elements
$("div").each(function()
{
// Check whether page is too long
if (height + $(this).outerHeight(true) > 1000)
{
// Create page break
$(this).before("<section contenteditable=\"false\"><h3>" + page_footer + "</h3><figure><hr /><hr /></figure><h1>" + page_header + "</h1><h2>" + page_count + ".</h2></section>");
// Adjust variables
page_count++; height = 0;
}
// Increment current page height
height += $(this).outerHeight(true);
});
}

What's the right way to run a javascript function without getting the object to "jump" right after the page loads

I have simple page with an object that gets a "top" property from the javascript.
How do I run the function without getting things on my page to "jump" ?
<script type="text/javascript">
function changeHeight () {
//Gets height
var h = window.innerHeight;
//alert(h);
console.log(h);
var categories = document.getElementById("cat").offsetHeight;
//alert(categories);
var x = 0.32 * categories;
var catTop = h - x;
//Gets cats
document.getElementById("cat").style.top = catTop+"px";
}
</script>
</head>
<body onload="changeHeight()" onresize="changeHeight()">
<div class="main">
<div class="cat" id="cat"></div>
</div>
</body>
</html>
I used "onload" on the tag to run the function. Which I know that's not so good.
The object jumps because you move it after the DOM has been rendered. That's what onload does: Make sure the DOM is complete and all loading/rendering has happened.
There are two solutions:
Put the script element after the node.
Use CSS to position the element
The first solution looks like this:
<div class="main">
<div class="cat" id="cat"></div>
<script>...</script>
</div>
At the time when the script is executed, the necessary DOM nodes are there. Unless your layout is complex, the offsets should be correct at this time. Note that many browsers start rendering while the page is loading. So there still might be a jump but less often, depending on the complexity of the page, browser optimizations, etc.
The second solution is to wrap your element in a container where you set the margin/padding until the cat element is naturally positioned correctly. The 0.32 would be translated to 32%. You need another element around it which has the correct height but which isn't visible.
To final solution should give body height: 100%, then add two containers inside. One for the content and the other to position the cat element. You will need to play with position style. Then
#cat { top: 32% }
should do the trick.

Automatically adjust div height to window size, but no smaller than children

I could use a little help with the following issue. What I've got is a fairly basic one-page website. Stripped down, it's structure looks pretty much like this:
<div class="full_height" id="home">
<div class="container">
<div class="row">
<div class="span8">
CONTENT GOES HERE
</div>
</div>
</div>
</div>
This div structure repeats 5 times, with consecutive id's [home, second, third, fourth, fifth]. The problem I'm having is that I'd like the .full_height containers to be the same size as the window upon loading the site and resize along with the window size upon resizing. In addition, the div's size should never become any smaller than it's children.
My current attempt looks like this:
$(window).on("resize load", resizeWindow);function resizeWindow( e ) {
var newWindowHeight = $(window).height()-160;
var idSelector = ["home","second","third","fourth","fifth"];
for (var i = 0; i < idSelector.length; i++) {
var element = document.getElementById(idSelector[i])
if( element.offsetHeight < element.scrollHeight){
$("#"+idSelector[i]).css("height", "auto" );
}
else{
$("#"+idSelector[i]).css("height", newWindowHeight );
}
}
}
Now, the script above sort of does what I'm looking for but with some hick-ups.
i) Upon loading the site it only adjusts the div height to the windows size, not meeting the children requirement. It only does this upon resizing the window.
ii) While resizing the window, the div height will flicker back and forth between "auto" and window size. Depending on when you stop resizing it will take either of the two sizes as its height.
Any ideas?
You need to start with 100% height all the way up the HTML tree:
html, body, #full_height {
height:100%;
}

Fix <div> to top until it reaches the end of it's container

I have the following code:
<div class="span4" style="height:1000px;">
<div id="iphone-frame">
<div id="iphone">
<div id="iframe-iphone">
<h1><div id="titlePreview"></div></h1>
<h2><div id="subtitlePreview"></div></h2>
<p><div id="contentPreview"></div></p>
</div>
</div>
<div id="iphone-shadow"></div>
</div>
What I am trying to do it write some Javascript so that <div id="iphone-frame"> fixes to the top of the window when it is scrolled past, until it gets the the end of it's container (<div id="span4">)
What I have tried:
Modifying this: http://jsfiddle.net/trepmal/e7GN8/
The jquery.scrollfollow.js plugin
Can anyone help?
I've created a fiddle as well (took note of your comment on Vector's answer) here: http://jsfiddle.net/asifrc/XLKmH/
I added the class sticker to the div you want to stick and changed the div selector in the css to sticker accordingly. The cloning business at the beginning of your code was redundant so i got rid of it.
I then added the following line that calculate's sticker's bottom:
var bottom = $('.sticker').parent().offset().top + $('.sticker').parent().height();
and then changed the if statement from if (dist >= fromtop) to
if (dist >= fromtop && dist <= bottom)
I then deleted the .hide() line as it was also redundant (to me, might've been useful to you somehow).
Let me know if this is what you were looking for, and if you have any questions :)
try this jsfiddle. It uses window scrolling stop detection from jQuery scroll() detect when user stops scrolling. And scrolls an element up/down based on $(window).scrollTop()

Categories