Scrolling news feed overlaps divs - javascript

I'm wanting to add a scrolling news feed to a small app I have built, however all the scripts or plugins I have seen so far have been for horizontal scrolling - whereas I'm wanting to scroll vertically.
I came across a question with this fiddle, http://jsfiddle.net/rNXs9/1/, which would work well for me. I would load each news item in to a div and then have it scroll.
I tried to implement this, but the DIVs overlap and become unreadable. See my fiddle here, https://jsfiddle.net/wgyxo8gv/.
I'm not very proficient with JS or CSS and so I'm not too sure what is causing this to happen and therefore how to fix it.
Here is the JS that is scrolling the items:
window.verticalScroller = function($elem) {
var top = parseInt($elem.css("top"));
var temp = -1 * $('#verticalScroller > div').height();
if(top < temp) {
top = $('#verticalScroller').height()
$elem.css("top", top);
}
$elem.animate({ top: (parseInt(top)-60) }, 600, function () {
window.verticalScroller($(this))
});
}
$(document).ready(function() {
var i = 0;
$("#verticalScroller > div").each(function () {
$(this).css("top", i);
i += 60;
window.verticalScroller($(this));
});
});
And the CSS for each DIV:
#verticalScroller {
position: absolute;
width:400px;
height: 500px;
border: 1px solid red;
overflow: hidden;
}
#verticalScroller > div{
position:absolute;
width:380px;
padding-left:10px;
height:auto;
border: dotted white;
overflow:hidden;
}
If anyone can point out how I can just get the divs to scroll one after the other without overlapping that would be great. Or if there is a plugin out there that works vertically rather than horizontally that works then that could work too - all my searches for vertical scrolling return endless pagination scripts.

I got around this by approaching this from a slightly different angle.
Instead of using divs, I used a list with the default styling removed and created a ticker function that just slid the list items up one every 5 seconds - the effect isn't quite continuous scrolling but it slides a news item up, pauses for it to be read and then continues on:
function tick(){
$('#ticker li:first').slideUp( function ()
(this).appendTo($('#ticker')).slideDown(); });
}
$(document).ready(function() {
setInterval(function(){ tick() }, 5000);
});
Fiddle

If you are already looking in adapt your first code you can do it this way.
$(document).ready(function() {
var i = 0;
var totalHeight = 0;
$("#verticalScroller > div").each(function () {
$(this).css("top", i);
i += $(this).height();
totalHeight = totalHeight + $(this).height();
});
var loop = setInterval(function(){ verticalScroller() }, 2000);
var index = 0;
function verticalScroller() {
var $currentChild = $("#verticalScroller > div").eq(index);
var scroll = $currentChild.height();
$("#verticalScroller > div").animate({ top: "-="+scroll }, 600, function() {
var top = totalHeight - $currentChild.height();
$currentChild.css({ top : top});
});
if(index == $("#verticalScroller > div").length-1) index = 0;
else index++;
}
});
#verticalScroller {
position: absolute;
width:400px;
height: 300px;
border: 1px solid red;
overflow: hidden;
background: silver;
}
#verticalScroller > div{
position:absolute;
width:380px;
padding: 0 10px;
height:auto;
border-bottom: dotted white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="verticalScroller">
<div>
Nude cyclist Nick Lowe identified as mystery rider in leopard G-string
<br>
A nude cyclist who caused a thong and dance in Marlborough has been exposed – he's Lower Hutt naturist Nick Lowe.
</div>
<div>
Josh Hazlewood pleads guilty to dissent after appeal rejected
<br>
Australian pace bowler Josh Hazlewood has pleaded guilty to dissent after reacting angrily when Black Cap Kane Williamson survived a contentious appeal and DRS review in the second test at Hagley Oval.
</div>
<div>
Firefighters attending increasing number of non-fire related and bizarre callouts
<br>
Rescuing ducklings stuck in drains, requests to fill water tanks and helping fellow firefighters' pet cockatoos - it's all part of the job for the fire service these days.
</div>
<div>
Mike Hosking gives his two cents on parenting
<br>
Mike Hosking thinks Kiwi teenagers have an "inflated sense of entitlement."
</div>
<div>
Australia cruising towards series victory after Black Caps' fight not enough
<br>
It's free entry at Hagley Oval and sadly too familiar for New Zealand against Australia on the final day of the test cricket summer.
</div>
<div>
Big fire strikes near Melbourne
<br>
A major bushfire is burning in the Melbourne area, with emergency services telling some residents it's too late to flee.
</div>
<div>
Smalltown GP offers $400k job and a slice of the business after struggling to recruit
<br>
A smalltown rural GP in the North Island is offering $400,000 to a junior doctor after a fruitless two-year search for staff.
</div>
<div>
Auckland Zoo's baby red pandas give warm fuzzies at weigh-in
<br>
Baby red panda twins at Auckland Zoo in Western Springs have had their first weigh-in and are cuter than ever.
</div>
<div>
Max Key reads ruthless messages directed at him
<br>
Max Key read out a list of mean social media posts with a smile on his face, even though he was the butt of every joke.
</div>
</div>

Change the following jquery function:
$(document).ready(function() {
var i = 0;
$("#verticalScroller > div").each(function () {
$(this).css("top", i);
i += $(this).height(); // CHANGE THIS
window.verticalScroller($(this));
});
});
Result: jsfiddle
When you set top for each div, you do not know the distance of each one of them from the top, because they have not fixed height. To set a correct top, you have to consider the real height of each div, that is why you have to change the line to i += $(this).height();.
If you want, you can add an addictional fixed amount of pixel to add some white space between the divs: i += $(this).height() + 10;.

Related

JS for-loop + if-statement: Catching last occurrence while conditionally updating text node

I have an array with a number of paragraphs which are to be placed inside a container until that container is »full«. Whatever does not fit into this container is to be placed into a separate container.
My solution mostly works fine, with a slight »cosmetic« error which I would like to fix.
My approach is to declare a maximum height for the container in which the text will be placed (0px at the beginning, due to it being empty). This max-height is equal to the height of the element wrapping the container, which has its height set via CSS.
I then place the content into a text node inside the first container by updating the nodeValue. Before each iteration, the height of the container is checked and as long as it is not taller than the parent which is wrapping it, the content is placed. As soon as the first container is »full« (= its height is equal to its parent's height), the remaining content is placed into the separate container.
I cannot simply place each whole paragraph, because if the last paragraph that is placed inside the first container is long enough to fill multiple lines (of course depending on the container's/parent's width), these lines will still end up in the first container and be cut off. Therefore, I'm iterating over each word of each paragraph, checking the height every time the nodeValueis updated.
This all works as expected, please see the attached snippet.
The only remaining issue is the last line of text inside the first container being only one word long. I know this happens of course because as soon as the nodeValue is being updated with this word, the container's height is recognised as too tall to fit more content and the script moves on to the next container.
Is there a way to »catch« that last word and make sure it also gets placed into the second container? Or alternatively fill the last line of the first container properly, but I assume that is more complicated. Appreciate any advice.
// Utilities
function update_NodeContent(newContent, container) {
var nodeContent_old = container.childNodes[0].nodeValue;
var nodeContent_add = newContent + " ";
var nodeContent_new = nodeContent_old + nodeContent_add;
container.childNodes[0].nodeValue = nodeContent_new;
}
// Variables
var cellHeight = $("#cell1").height();
// Content
var content = [
"The quick, brown fox jumps over a lazy dog. DJs flock by when MTV ax quiz prog. Junk MTV quiz graced by fox whelps. Bawds jog, flick quartz, vex nymphs. Waltz, bad nymph, for quick jigs vex!",
"Fox nymphs grab quick-jived waltz. Brick quiz whangs jumpy veldt fox. Bright vixens jump; dozy fowl quack. Quick wafting zephyrs vex bold Jim. Quick zephyrs blow, vexing daft Jim. Sex-charged fop blew my junk TV quiz.",
"How quickly daft jumping zebras vex. Two driven jocks help fax my big quiz. Quick, Baz, get my woven flax jodhpurs! »Now fax quiz Jack!« my brave ghost pled. Five quacking zephyrs jolt my wax bed.",
"Flummoxed by job, kvetching W. zaps Iraq. Cozy sphinx waves quart jug of bad milk. A very bad quack might jinx zippy fowls. Few quips galvanized the mock jury box. Quick brown dogs jump over the lazy fox."
]
function placeText() {
while (content.length) {
var node = document.createTextNode("");
$("#cell1 .container").append(node);
//
var content_words = content[0].split(" ");
for (var i = 0; i < content_words.length; i++) {
//
var textBlockHeight = $("#cell1 .container").height();
if (textBlockHeight < cellHeight) {
update_NodeContent(content_words[i], $('#cell1 .container')[0]);
} else {
update_NodeContent(content_words[i], $('#cell2 .container')[0]);
}
}
//
var itemtoRemove = content[0];
content.shift();
}
}
// Execution
placeText();
:root {
--height_line_single: 19px;
--height_textBlock: calc(var(--height_line_single) * 14);
}
body {
font-size: 16px;
line-height: 1.2;
}
p {
margin: 0 0 1rem 0;
}
p.noMargin {
margin: 0;
}
.article {
width: 90vw;
}
.text-block {
height: var(--height_textBlock);
overflow: hidden;
background: lightgreen;
margin-bottom: 1rem;
}
#cell1 {
width: calc(100%/3);
}
#cell2 {
column-count: 3;
column-fill: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="article">
<div id="cell1" class="text-block">
<div class="container">
</div>
</div>
<div id="cell2" class="text-block">
<div class="container">
</div>
</div>
</div>
Here's a working example. The selectors and heights could be changed to use the jQuery versions if you desire. You didn't not finalize looping through the content in your example above, so I'll leave that for you to add.
This example can also be viewed on CodePen: https://codepen.io/edlucas/pen/MWYrybK
// Utilities
function update_NodeContent(newContent, container) {
// Ensure that we start with an empty string
var nodeContent_old = container.innerHTML ? container.innerHTML : '';
container.innerHTML = nodeContent_old + newContent + " ";
}
// Content
var content = [
"The quick, brown fox jumps over a lazy dog. DJs flock by when MTV ax quiz prog. Junk MTV quiz graced by fox whelps. Bawds jog, flick quartz, vex nymphs. Waltz, bad nymph, for quick jigs vex!",
"Fox nymphs grab quick-jived waltz. Brick quiz whangs jumpy veldt fox. Bright vixens jump; dozy fowl quack. Quick wafting zephyrs vex bold Jim. Quick zephyrs blow, vexing daft Jim. Sex-charged fop blew my junk TV quiz.",
"How quickly daft jumping zebras vex. Two driven jocks help fax my big quiz. Quick, Baz, get my woven flax jodhpurs! »Now fax quiz Jack!« my brave ghost pled. Five quacking zephyrs jolt my wax bed.",
"Flummoxed by job, kvetching W. zaps Iraq. Cozy sphinx waves quart jug of bad milk. A very bad quack might jinx zippy fowls. Few quips galvanized the mock jury box. Quick brown dogs jump over the lazy fox."
]
var containerHeight = document.querySelector('#cell1').clientHeight;
function placeText() {
if (content.length) {
var content_words = content[0].split(" ");
var holdContent = "";
var useSecondContainer = false;
var $textBlock1 = document.querySelector('#cell1 .container');
var $textBlock2 = document.querySelector('#cell2 .container');
var textBlockHeight = 0;
var word = '';
for (var i = 0; i < content_words.length; i++) {
word = content_words[i];
// Ensure that we have a word to display
if (word && word.trim()) {
textBlockHeight = $textBlock1.clientHeight;
// If we have not already exceeded the first container
if (textBlockHeight <= containerHeight && !useSecondContainer) {
// Add to first container
holdContent = $textBlock1.innerHTML;
update_NodeContent(word, $textBlock1);
// If we exceed the height with this addition, restore the contents to the
// last state and add this word to the second container
if ($textBlock1.clientHeight > containerHeight) {
// Restore last good content
$textBlock1.innerHTML = holdContent;
// Add to the second container
useSecondContainer = true;
update_NodeContent(word, $textBlock2);
}
} else {
// Add to the second container
update_NodeContent(word, $textBlock2);
}
}
}
}
}
// Execution
placeText();
:root {
--height_line_single: 19px;
--height_textBlock: calc(var(--height_line_single) * 2);
}
body {
font-size: 16px;
line-height: 1.2;
}
p {
margin: 0 0 1rem 0;
}
p.noMargin {
margin: 0;
}
.article {
width: 90vw;
}
.text-block {
height: var(--height_textBlock);
overflow: hidden;
background: lightgreen;
margin-bottom: 1rem;
}
#cell1 {
width: calc(100%/3);
}
#cell2 {
column-count: 3;
column-fill: auto;
}
<div class="article">
<div id="cell1" class="text-block">
<div class="container">
</div>
</div>
<div id="cell2" class="text-block">
<div class="container">
</div>
</div>
</div>

Only allow scrolling to stop on certain elements

I've tried searching to see if there's already a question about this but can't find anything - so apologies if this is in fact a duplicate!
I've seen on some websites a feature where, when scrolling, the scroll stop point is forced to stop at a specific element rather than just wherever the user actually stopped scrolling.
I imagine this can be achieved via jQuery, but can't seem to find any documentation or help articles about it.
So, here's some example HTML...
<div id="one" class="block"></div>
<div id="two" class="block"></div>
<div id="three" class="block"></div>
With this as the CSS...
#one {
background: red;
}
#two {
background: green;
}
#three {
background: yellow;
}
.block {
width: 200px;
height: 100vh;
}
And what I'm looking to achieve is that when the user scrolls their browser from div 'one' to div 'two', once they've started scrolling over div 'two' and they then stop scrolling the browser automatically jumps them so that they see div 'two' in full, rather than a bit of the bottom of div 'one' and then most of div 'two' - I've definitely seen it done before but no idea how!
I hope this makes sense, and thanks in advance for any help or insight anyone can offer...
I don't remember too well, but I guess there are many ways to achieve what you want. One thing that came to my mind is to wrap around your divs and make a separate hidden div with full height. I did this adhoc solution below:
Once scroll approaches a threshold, I move to the div I should be looking at and vice versa. Here is a working solution FIDDLE:
HTML
<div id="phantom"></div>
<div id="wrapper">
<div id="one" class="block"></div>
<div id="two" class="block"></div>
<div id="three" class="block"></div>
</div>
CSS
#one {
background: red;
}
#two {
background: green;
}
#three {
background: yellow;
}
.block {
width: 200px;
height: 100vh;
}
#wrapper {
overflow:hidden;
position:fixed;
top:0px;
}
#phantom {
visibility:hidden;
}
JS
!function(){
//the array of divs
var divs = Array.prototype.slice.call(document.getElementsByClassName("block")), count = divs.length,
wrapper = document.getElementById("wrapper"),
phantom = document.getElementById("phantom"),
//the speed of scroll
scrollStep = 5,
//total length of phantom div
totalLength = Array.prototype.slice.call(wrapper.children).reduce(function(ac,d,i,a){return ac += d.clientHeight},0),
//store the animation frame here
currentFrame;
//wrapper is overflow hidden
wrapper.style.height = totalLength/count + "px";
//phantom has full height
phantom.style.height = totalLength + "px";
//add listener for scroll
window.addEventListener("scroll",function(){
//throttle the function
if(this._busy){return};
this._busy = true;
var that = this;
window.requestAnimationFrame(function(){
that._busy = false;
var heightOfDocument = Math.max(document.documentElement.scrollHeight,document.body.scrollHeight),
totalScroll = Math.max(document.body.scrollTop,document.documentElement.scrollTop),
//which element should we look at?
whichElement = Math.round(totalScroll/heightOfDocument*count);
//if we are already around, don't do anything
if(divs[whichElement]._current){
return;
} else {
//cancel the last animation if any and start a new one
window.cancelAnimationFrame(currentFrame);
divs.forEach(function(d,i){delete d._current});
moveTo(divs[whichElement]);
}
});
},false);
//helper function to linearly move to elements
function moveTo(node){
node._current = true;
var top = node.offsetTop,
current = node.parentNode.scrollTop,
distance = top - current,
step = distance < 0 ? -scrollStep : scrollStep;
if(Math.abs(distance) < scrollStep){
node.parentNode.scrollTop = top;
return;
} else {
node.parentNode.scrollTop += step;
}
//store the current frame
currentFrame = window.requestAnimationFrame(function(){
moveTo(node);
});
}
}();
You obviously need to attach 'resize' event to update the values of the totalLength and set the correct new length on wrapper and phantom. You can also implement a easing function to modify the scrolling behavior to your taste. I leave them to you as homework.

jquery background image scroll effect speed issue

I have purchased a template for my shopify store that scrolls a site wide absolutely positioned background image at a slower speed than what the user scrolls for a neato perspective effect.
I have found the script used in the template that animated the scrolling effect for the background image. It is as follows:
<script type="text/javascript">
(function($) {
if(device.desktop()){
// PARALLAX INIT
$(window).bind('scroll',function(e){
parallaxScroll1();
});
function parallaxScroll1(){
var scrolled = $(window).scrollTop();
$('#wrapper .wrapper_bg').css('top',(0+(scrolled*.75))+'px');
}
// SMOOTHSCROLL 4 WEBKIT
var platform = navigator.platform.toLowerCase();
if (platform.indexOf('win') == 0 || platform.indexOf('linux') == 0) {
if ($.browser.webkit) {
/* jquery.simplr.smoothscroll - https://github.com/simov/simplr-smoothscroll */
;(function(e){"use strict";e.srSmoothscroll=function(t){var n=e.extend({step:85,speed:600,ease:"linear"},t||{});var r=e(window),i=e(document),s=0,o=n.step,u=n.speed,a=r.height(),f=navigator.userAgent.indexOf("AppleWebKit")!==-1?e("body"):e("html"),l=false;e("body").mousewheel(function(e,t){l=true;if(t<0)s=s+a>=i.height()?s:s+=o;else s=s<=0?0:s-=o;f.stop().animate({scrollTop:s},u,n.ease,function(){l=false});return false});r.on("resize",function(e){a=r.height()}).on("scroll",function(e){if(!l)s=r.scrollTop()})}})(jQuery);
/* jquery.mousewheel - https://github.com/jquery/jquery-mousewheel */
!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof exports?module.exports=a:a(jQuery)}(function(a){function b(b){var g=b||window.event,h=i.call(arguments,1),j=0,l=0,m=0,n=0,o=0,p=0;if(b=a.event.fix(g),b.type="mousewheel","detail"in g&&(m=-1*g.detail),"wheelDelta"in g&&(m=g.wheelDelta),"wheelDeltaY"in g&&(m=g.wheelDeltaY),"wheelDeltaX"in g&&(l=-1*g.wheelDeltaX),"axis"in g&&g.axis===g.HORIZONTAL_AXIS&&(l=-1*m,m=0),j=0===m?l:m,"deltaY"in g&&(m=-1*g.deltaY,j=m),"deltaX"in g&&(l=g.deltaX,0===m&&(j=-1*l)),0!==m||0!==l){if(1===g.deltaMode){var q=a.data(this,"mousewheel-line-height");j*=q,m*=q,l*=q}else if(2===g.deltaMode){var r=a.data(this,"mousewheel-page-height");j*=r,m*=r,l*=r}if(n=Math.max(Math.abs(m),Math.abs(l)),(!f||f>n)&&(f=n,d(g,n)&&(f/=40)),d(g,n)&&(j/=40,l/=40,m/=40),j=Math[j>=1?"floor":"ceil"](j/f),l=Math[l>=1?"floor":"ceil"](l/f),m=Math[m>=1?"floor":"ceil"](m/f),k.settings.normalizeOffset&&this.getBoundingClientRect){var s=this.getBoundingClientRect();o=b.clientX-s.left,p=b.clientY-s.top}return b.deltaX=l,b.deltaY=m,b.deltaFactor=f,b.offsetX=o,b.offsetY=p,b.deltaMode=0,h.unshift(b,j,l,m),e&&clearTimeout(e),e=setTimeout(c,200),(a.event.dispatch||a.event.handle).apply(this,h)}}function c(){f=null}function d(a,b){return k.settings.adjustOldDeltas&&"mousewheel"===a.type&&b%120===0}var e,f,g=["wheel","mousewheel","DOMMouseScroll","MozMousePixelScroll"],h="onwheel"in document||document.documentMode>=9?["wheel"]:["mousewheel","DomMouseScroll","MozMousePixelScroll"],i=Array.prototype.slice;if(a.event.fixHooks)for(var j=g.length;j;)a.event.fixHooks[g[--j]]=a.event.mouseHooks;var k=a.event.special.mousewheel={version:"3.1.12",setup:function(){if(this.addEventListener)for(var c=h.length;c;)this.addEventListener(h[--c],b,!1);else this.onmousewheel=b;a.data(this,"mousewheel-line-height",k.getLineHeight(this)),a.data(this,"mousewheel-page-height",k.getPageHeight(this))},teardown:function(){if(this.removeEventListener)for(var c=h.length;c;)this.removeEventListener(h[--c],b,!1);else this.onmousewheel=null;a.removeData(this,"mousewheel-line-height"),a.removeData(this,"mousewheel-page-height")},getLineHeight:function(b){var c=a(b),d=c["offsetParent"in a.fn?"offsetParent":"parent"]();return d.length||(d=a("body")),parseInt(d.css("fontSize"),10)||parseInt(c.css("fontSize"),10)||16},getPageHeight:function(b){return a(b).height()},settings:{adjustOldDeltas:!0,normalizeOffset:!0}};a.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})});
$.srSmoothscroll({
step: 55,
speed: 100,
ease: 'swing'
});
}
};
};
})(jQuery);
</script>
The issue that I am having is that the scrolling effect moves to quickly, and by the time the user has reached the bottom of the page they are viewing, the background image has prematurely cut off.
I have been fidling around with the values in this script, trying to slow down the effect, with no success. Any insights?
Thanks! You can view this script in action on our site at:
http://ts8276eb.myshopify.com/
the password is: yandasmusic
That code is way too complicated for me to even consider trying to debug.
So I made a much simpler version.
var wrapper = document.getElementById('wrapper'),
checkbox = document.getElementById('scrolleffect');
function parallax() {
if( checkbox.checked) {
wrapper.style.backgroundPosition = "center " + (this.scrollTop / (this.scrollHeight - window.innerHeight) * 100) + "%";
}
else {
wrapper.style.backgroundPosition = "";
}
}
document.body.onscroll = function() {parallax.call(document.body);};
document.documentElement.onscroll = function() {parallax.call(document.documentElement);};
#wrapper {
background: #333 url('http://cdn.shopify.com/s/files/1/0810/2125/t/21/assets/body_bg_img.png?677044079657970527') no-repeat scroll center top;
color: white;
padding: 8px;
}
.spacer {
height: 800px;
}
body {
margin: 0;
}
<div id="wrapper">
<p>Content!</p>
<p style="position: fixed;"><label><input type="checkbox" id="scrolleffect" /> Toggle background scroll effect</label></p>
<div class="spacer"></div>
<p>More content!</p>
<div class="spacer"></div>
<p>Content ends</p>
</div>
The important part here is that the background position is updated according to how far down the page we've scrolled. It ranges from center 0% to center 100%. The convenient thing about background image positioning is that 0% means "align top of image with top of element", and 100% means "align bottom of image with bottom of element". Values are interpolated in-between, so 25% would be "align the top quarter mark of the image with the top quarter mark of the element".
Much simpler.
The numbers appear to be crunched here:
$('#wrapper .wrapper_bg').css('top',(0+(scrolled*.75))+'px');
So it currently scrolls 25% slower than the page. If you lower this number, it will go more slowly...
$('#wrapper .wrapper_bg').css('top',(0+(scrolled*.25))+'px');

Scrolling News Ticker Jquery - Issues

Original Source & Example:
http://www.htmldrive.net/items/show/397/Vertical-Scrolling-News-Ticker-With-jQuery-jCarouse
Hello Again!! Scrolling News Ticker Jquery with some issues:
First Issue : Internet Explorer Error Message
" Object doesn't support this property or method " Line: 269: Line 269)
ticker.mouseenter(function() { // <---Line: 269
//stop current animation
ticker.children().stop();
});
Second Issue : The only way of clicking on a news option (to be directed to the link of a page) is through the text title that in the website example is in blue color.
I would like for the user to be able to click on the whole section of the option that
includes the image aswell.
Third Issue : When the news scrolls it looks all in one, is there a way to add a line to separate each section.
Forth Issue: Is there a way to pause the automatic scrolling when a user puts the mouse
over a section?
Is there a way to add more text under the title and category?
Here is the script itself with the IE issue highlighted with an arrow on the right hand side
below:
<script type="text/javascript">
$(function() {
//cache the ticker
var ticker = $("#ticker");
//wrap dt:dd pairs in divs
ticker.children().filter("dt").each(function() {
var dt = $(this),
container = $("<div>");
dt.next().appendTo(container);
dt.prependTo(container);
container.appendTo(ticker);
});
//hide the scrollbar
ticker.css("overflow", "hidden");
//animator function
function animator(currentItem) {
//work out new anim duration
var distance = currentItem.height();
duration = (distance + parseInt(currentItem.css("marginTop"))) / 0.020;
//animate the first child of the ticker
currentItem.animate({ marginTop: -distance }, duration, "linear", function() {
//move current item to the bottom
currentItem.appendTo(currentItem.parent()).css("marginTop", 0);
//recurse
animator(currentItem.parent().children(":first"));
});
};
//start the ticker
animator(ticker.children(":first"));
//set mouseenter
ticker.mouseenter(function() {
ticker.mouseenter(function() { // <---Line: 269
//stop current animation
ticker.children().stop();
});
//set mouseleave
ticker.mouseleave(function() {
//resume animation
animator(ticker.children(":first"));
});
});
</script>
I would deeply appreciate it!!
to add line to separate each items add border-bottom:1px solid black; to the css.
after read your question i would like to show you the javascript method that i used in my site and stops when mouse over.
<div id="marqueecontainer" onMouseover="copyspeed=pausespeed" onMouseout="copyspeed=marqueespeed">
<div id="vmarquee" style="position: absolute; width: 98%;">
<!--YOUR SCROLL CONTENT HERE-->
<!--YOUR SCROLL CONTENT HERE-->
</div>
</div><style type="text/css">
#marqueecontainer{
position: relative;
width: 200px; /*marquee width */
height: 200px; /*marquee height */
background-color: white;
overflow: hidden;
border: 3px solid orange;
padding: 2px;
padding-left: 4px;
}
</style>
<script type="text/javascript">
var delayb4scroll=2000 //Specify initial delay before marquee starts to scroll on page (2000=2 seconds)
var marqueespeed=2 //Specify marquee scroll speed (larger is faster 1-10)
var pauseit=1 //Pause marquee onMousever (0=no. 1=yes)?
var copyspeed=marqueespeed
var pausespeed=(pauseit==0)? copyspeed: 0
var actualheight=''
function scrollmarquee(){
if (parseInt(cross_marquee.style.top)>(actualheight*(-1)+8))
cross_marquee.style.top=parseInt(cross_marquee.style.top)-copyspeed+"px"
else
cross_marquee.style.top=parseInt(marqueeheight)+8+"px"
}
function initializemarquee(){
cross_marquee=document.getElementById("vmarquee")
cross_marquee.style.top=0
marqueeheight=document.getElementById("marqueecontainer").offsetHeight
actualheight=cross_marquee.offsetHeight //height of marquee content (much of which is hidden from view)
if (window.opera || navigator.userAgent.indexOf("Netscape/7")!=-1){ //if Opera or Netscape 7x, add scrollbars to scroll and exit
cross_marquee.style.height=marqueeheight+"px"
cross_marquee.style.overflow="scroll"
return
}
setTimeout('lefttime=setInterval("scrollmarquee()",30)', delayb4scroll)
}
if (window.addEventListener)
window.addEventListener("load", initializemarquee, false)
else if (window.attachEvent)
window.attachEvent("onload", initializemarquee)
else if (document.getElementById)
window.onload=initializemarquee
</script>
you can view the demo at here

Animate photo (or div) inside a frame div

The picture is pretty much explanatory by itself. The div "behind" contains a bunch of little square photos that I want to animate smoothly. I'm really not good with jQuery animations, could anyone help me out with this?
(Window is fixed, pictures move "inside" it, animating forever since the page load)
You could do something like this
markup:
<div id="mask">
<img id="pic" alt="my img" src="http://www.destination360.com/north-america/us/idaho/images/s/idaho-sawtooth-mountains.jpg">
</div>
css:
#mask{
overflow:hidden;
width:100px;
height:100px;
position:absolute;
border:5px solid #000000;
}
#mask img{
border:none;
position:absolute;
}
js:
$('#pic').animate({left:-200},3000).animate({top:-50},3000); /* and so on... */
fiddle:
http://www.jsfiddle.net/steweb/YHAZ9/
Edit (looping it forever) http://www.jsfiddle.net/steweb/YHAZ9/4/
I'm a fan of SIN/COS functions, so let me share with you my shot at this problem.
The idea is to have a function that runs forever, and as soon as possible so that the animation is smooth. I use a sin/cos functions to determine the new x (left) and y (top) coordenates of the div, and I have a series of parameters that allow the configuration of the speed and range of the animation.
Just paste this into an HTML file and test it in your browser.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
</head>
<body>
<div id="stuff" style="background: red; width: 200px; height: 200px; margin: auto; position: relative;">
a b c<br />
d e f<br />
g h i<br />
j k l<br />
</div>
<script>
var start = new Date();
var x_speed = 0.001, // bigger ---> faster
y_speed = 0.01, // bigger ---> faster
x_multiplier = 300, // how far away I can go on the X axis
y_multiplier = 20, // how far away I can go on the Y axis
x_offset = 0,
y_offset = 0;
function animate() {
var now = new Date();
var elapsed_time = now - start;
var x = Math.sin((elapsed_time)*x_speed) * x_multiplier + x_offset;
var y = Math.cos((elapsed_time)*y_speed) * y_multiplier + y_offset;
$("#stuff").css({
left : x,
top : y
});
setTimeout(animate, 0);
}
setTimeout(animate, 76);
</script>
</body>
</html>
For how long? After a click?
I'm not behind my own computer right now, but try something like this:
This is for after a click:
$("#frame").click(
function(){
$("#photo").animate({"left": "-=100px"}, function(){
$("#photo").animate({"top": "-=100px"}, function(){
$("#photo").animate({"left": "=100px"});
});
});
});
And so forth, after each line you can put a new line, like i did in line 3 and 4 from the code. This way the photo behind moves in a square.
Just a suggestion, don't know if this is exactly what you want.
EDIT: Btw, you can only go left, right or up and down, what might smoothen your animation is to grow the photo and shrink it. Therefore you need for instance the "width" parameter.
Check the jQuery site here.

Categories