Implementing fluid JS tile interface - javascript

I'm building a photography website, and I want to create a nice "tiled" interface, which will look similar to the interface on new version MSN Money Now (note - the new version of the website can be viewed only on Windows 8 PCs) - http://t.money.msn.com/now/. I tried to implement this in Javascript.
Here is a sample page with prefilled data: http://photoachiever.azurewebsites.net/en
I created Tile groups - each 2 units high, 2 units wide, which can contain either one big square tile, two wide tiles or four small square tiles. Now, because I want the site to be responsive, I wanted to calculate on the fly in Javascript the optimal unit size, so that always 100 % of the space are filled and for wider screens are for example more columns visible and so on. It works the same way on MSN Money website, but there are two important differences:
1) When my images load the first time, I just see them in their highest resultion up until the point where all images are loaded and the JS is executed. The MSN Money web just displays a green area and the images later appear, already resized appropriately.
2) When I resize the window, it is far from fluid and the caluclations and mainly image resizing are very significantly visible. On MSN Money however the resizing is very smooth and even the images seem to just resize without a glitch. Also - they managed to make the fonts resize fluidly.
Could you please explain me, how the MSN Money website achieved these results?
I have seen a few similare questions here on Stack Overflow, but they never required the equal width and height of individual tiles, which I really need for my design.
Bonus question: Could you please add some explanations of how to achieve responsive animated reflow of divs? Example found on http://www.brainyquote.com/ - when you change Window size, it reflows all quotes in an animated manner.
Edit:
I'm attaching my current code, which is far from correct (preformance is very low and images appear too large first and their size drops a after they all download).
First part of the code (attaches all events to the tiles and adds animation on click):
function attachTileEvents() {
if ($(".tile-flow").size() >= 1) {
$(window).resize(function () {
delay(function () {
resizeTiles();
}, 100);
});
$(document).on("click", ".tile-flow .load-next-page", manualLoadContentDetection);
$(window).on("scroll", scrollLoadContentDetection);
$(document).on("touchend", scrollLoadContentDetection);
}
resizeTiles();
$(".tile .contents").each(function () {
var tile = $(this).parent()[0]
var mouse = { x: 0, y: 0, down: false };
var maxRotation = 16;
var minScale = 0.95;
var setRotation = function (scaled) {
//Rotations as percentages
var width = tile.offsetWidth;
var height = tile.offsetHeight;
var diag = Math.sqrt((width / 2) * (width / 2) + (height / 2) * (height / 2));
var dist = Math.sqrt((mouse.x - (width / 2)) * (mouse.x - (width / 2)) + (mouse.y - (height / 2)) * (mouse.y - (height / 2)));
var fract = 1.0;
if (dist > 0) {
fract = dist / diag;
}
var yRotation = (mouse.x - (width / 2)) / (width / 2);
var xRotation = (mouse.y - (height / 2)) / (height / 2);
if (scaled) {
tile.style.webkitTransform = "rotateX(" + -xRotation * maxRotation + "deg)" + " rotateY(" + yRotation * maxRotation + "deg)" + " scale(" + (minScale + fract * (1 - minScale)) + ")";
tile.style.mozTransform = "rotateX(" + -xRotation * maxRotation + "deg)" + " rotateY(" + yRotation * maxRotation + "deg)" + " scale(" + (minScale + fract * (1 - minScale)) + ")";
tile.style.transform = "rotateX(" + -xRotation * maxRotation + "deg)" + " rotateY(" + yRotation * maxRotation + "deg)" + " scale(" + (minScale + fract * (1 - minScale)) + ")";
} else {
tile.style.webkitTransform = "rotateX(" + -xRotation * maxRotation + "deg)" + " rotateY(" + yRotation * maxRotation + "deg)";
tile.style.mozTransform = "rotateX(" + -xRotation * maxRotation + "deg)" + " rotateY(" + yRotation * maxRotation + "deg)";
tile.style.transform = "rotateX(" + -xRotation * maxRotation + "deg)" + " rotateY(" + yRotation * maxRotation + "deg)";
}
}
var MouseDown = function (e) { mouse.x = e.offsetX; mouse.y = e.offsetY; mouse.down = true; setRotation(true); }
var MouseUp = function (e) { if (mouse.down) { mouse.down = false; tile.style.webkitTransform = "rotateX(0deg)" + " rotateY(0deg) scale(1.0)"; tile.style.mozTransform = "rotateX(0deg)" + " rotateY(0deg) scale(1.0)"; tile.style.transform = "rotateX(0deg)" + " rotateY(0deg) scale(1.0)"; } }
var MouseOut = function (e) { mouse.down = false; tile.style.webkitTransform = "rotateX(0deg)" + " rotateY(0deg) scale(1.0)"; tile.style.mozTransform = "rotateX(0deg)" + " rotateY(0deg) scale(1.0)"; tile.style.transform = "rotateX(0deg)" + " rotateY(0deg) scale(1.0)"; }
var MouseMove = function (e) { mouse.x = e.offsetX; mouse.y = e.offsetY; if (mouse.down == true) { setRotation(false); } }
$(tile).on("mousemove", MouseMove);
$(tile).on("mousedown", MouseDown);
$(tile).on("mouseup", MouseUp);
$(tile).on("mouseout", MouseOut);
});}
And the main part - resizing:
var TileSizes = { wideWidth: 0, singleWidth: 0, margin: 0 };
function resizeTiles() {
var rowColumnNumber = 2;
var width = $(window).width();
if (width >= 2500) {
rowColumnNumber = 7;
}
else if (width >= 2000) {
rowColumnNumber = 6;
} else if (width >= 1600) {
rowColumnNumber = 5;
} else if (width >= 1280) {
rowColumnNumber = 4;
} else if (width >= 768) {
rowColumnNumber = 3;
} else if (width >= 480) {
rowColumnNumber = 2;
} else {
rowColumnNumber = 1;
}
var totalWidth = $(".tile-flow").width() - 17; //compensate for the scrollbar
//calculate the margin size : 5% of the flow width
var margin = Math.round(totalWidth * 0.05 / rowColumnNumber);
var wideSize = Math.floor((totalWidth - margin * (rowColumnNumber - 1)) / rowColumnNumber);
var halfSize = Math.floor((wideSize - margin) / 2);
var quaterSize = Math.floor(halfSize * 2.5 / 3);
var heightSize = Math.floor(halfSize * 2 / 2.0);
var doubleHeightSize = heightSize * 2 + margin;
var detailsSize = quaterSize * 2 + margin;
TileSizes.wideWidth = doubleHeightSize;
TileSizes.singleWidth = heightSize;
TileSizes.margin = margin;
$(".big-square-tile").width(doubleHeightSize);
$(".big-square-tile").height(doubleHeightSize);
$(".wide-tile").width(doubleHeightSize);
$(".small-tile").width(halfSize);
$(".tile-flow .col .small-tile:even").css("margin-right", margin);
$(".small-tile").height(heightSize);
$(".wide-tile").height(heightSize);
$(".col").width(doubleHeightSize);
$(".col").css("margin-right", margin);
$(".col:nth-child(" + rowColumnNumber + "n)").css("margin-right", 0);
//all tiles get bottom margin
var how = 0;
$(".wide-tile .contents footer").each(function () {
if ((how % 4 == 0) || (how % 4 == 1)) {
$(this).width(TileSizes.singleWidth - 20);
} else {
$(this).height(75);
}
if (how % 4 == 0) {
$(this).css("left", TileSizes.wideWidth);
} else if (how % 4 == 1) {
$(this).css("left", -TileSizes.singleWidth);
}
else if (how % 4 == 2) {
$(this).css("top", TileSizes.singleWidth);
} else {
$(this).css("top", -95);
}
how = how + 1;
});
$(".big-square-tile .contents footer").each(function () {
$(this).height(75);
if (how % 2 == 0) {
$(this).css("top", TileSizes.wideWidth);
} else {
$(this).css("top", -95);
}
how = how + 1;
});
$(".small-tile .contents footer").each(function () {
$(this).width(TileSizes.singleWidth - 20);
$(this).height(TileSizes.singleWidth - 20);
if (how % 4 == 0) {
$(this).css("left", TileSizes.singleWidth);
} else if (how % 4 == 1) {
$(this).css("left", -TileSizes.singleWidth);
}
else if (how % 4 == 2) {
$(this).css("top", TileSizes.singleWidth);
} else {
$(this).css("top", -TileSizes.singleWidth);
}
how = how + 1;
});
$(".tile").css("margin-bottom", margin);
//resize images
var imageList = Array();
$(".big-square-tile img").each(function () {
imageList.push($(this));
var img = new Image();
img.onload = function () {
var originalHeight = this.height;
var originalWidth = this.width;
var index = parseInt(this.id.replace("RESIZINGBIG", ""));
if (originalHeight > originalWidth) {
imageList[index].css("height", "auto");
imageList[index].css("width", "100%");
} else {
imageList[index].css("height", "100%");
imageList[index].css("width", "auto");
}
}
img.id = "RESIZINGBIG" + (imageList.length - 1);
img.src = $(this).attr('src');
});
$(".small-tile img").each(function () {
imageList.push($(this));
var img = new Image();
img.onload = function () {
var originalHeight = this.height;
var originalWidth = this.width;
var index = parseInt(this.id.replace("RESIZINGSMALL", ""));
if (originalHeight > originalWidth) {
imageList[index].css("height", "auto");
imageList[index].css("width", "100%");
} else {
imageList[index].css("height", "100%");
imageList[index].css("width", "auto");
}
}
img.id = "RESIZINGSMALL" + (imageList.length - 1);
img.src = $(this).attr('src');
});
$(".wide-tile img").each(function () {
$(this).css("height", "auto");
$(this).css("width", "100%");
});}
And here is a sample of how the HTML code looks now:
<div class="tile-flow">
<div class="tile-row">
<div class="col">
<div class="tile big-square-tile">
<div class="contents">
<img src="~/Images/Test/5.jpg" />
<footer>
<h1>Test</h1>
<span class="author">by Test</span>
</footer>
</div>
</div>
</div>
<div class="col">
<div class="tile small-tile">
<div class="contents">
<img src="~/Images/Test/2.jpg" />
<footer>
<h1>Test</h1>
<span class="author">by Test</span>
</footer>
</div>
</div>
<div class="tile small-tile">
<div class="contents">
<img src="~/Images/Test/3.jpg" />
<footer>
<h1>Test</h1>
<span class="author">by Test</span>
</footer>
</div>
</div>
<div class="tile wide-tile">
<div class="contents">
<img src="~/Images/Test/4.jpg" />
<footer>
<h1>Test</h1>
<span class="author">by Test</span>
</footer>
</div>
</div>
</div>
<div class="col">
<div class="tile big-square-tile">
<div class="contents">
<img src="~/Images/Test/6.jpg" />
<footer>
<h1>Test</h1>
<span class="author">by Test</span>
</footer>
</div>
</div>
</div>
<div class="col">
<div class="tile wide-tile">
<div class="contents">
<img src="~/Images/Test/1.jpg" />
<footer>
<h1>Test</h1>
<span class="author">by Test</span>
</footer>
</div>
</div>
<div class="tile wide-tile">
<div class="contents">
<img src="~/Images/Test/7.jpg" />
<footer>
<h1>Test</h1>
<span class="author">by Test</span>
</footer>
</div>
</div>
</div>
</div>
</div>

If I were you I would use Isotope for the basic layout and add the slide shows and click events along side it. You can insert most any content you like. jQuery Isotope.
Updated Working Model
Full page result
JS
$(function () {
var $container = $('#container');
$container.imagesLoaded(function () {
$container.isotope({
itemSelector: '.photo'
});
});
});
var $container = $('#container');
// initialize Isotope
$container.isotope({
// options...
resizable: false, // disable normal resizing
// set columnWidth to a percentage of container width
masonry: {
columnWidth: $container.width() / 5
}
});
// update columnWidth on window resize
$(window).smartresize(function () {
$container.isotope({
// update columnWidth to a percentage of container width
masonry: {
columnWidth: $container.width() / 5
}
});
});
//click function
$(function () {
$('.photo').click(function () {
$(this).toggleClass('red');
});
});
//hover function
$(function () {
$('#photo1').hover(function () {
$('#info1').fadeToggle();
});
});
Proof of concept- Animations inside Isotope
Note this animation is total kludge fine tune before using.
function animatie() {
var d = 0;
for (var i = 0; i < 3; ++i) {
var b = "#info" + i;
$(b).css('background', 'silver');
$(b).hide().delay(d).slideDown(1000).delay(3000).slideUp(1000);
d += 5000;
}
}
animatie();
window.setInterval(animatie, 15000);
$(function () {
for (var i = 0; i < 3; ++i) {
var z = '.box' + i;
var divHeight = $(z).height();
$(z).css('max-height', divHeight + 'px');
$(z).css('max-height', divHeight + 'px');
$(z).css('overflow', 'hidden');
}
});
$(window).resize(function () {
for (var i = 0; i < 3; ++i) {
var z = '.box' + i;
var divHeight = $(z).height();
$(z).css('max-height', divHeight + 'px');
$(z).css('overflow', 'hidden');
}
});
This is a very cool plugin for layout, sorting, and filtering. It will give you the tiles and animations as basic features.
Fluid Isotope
Images Loaded Plugin
Infinite Scroll
Added animation inside Isotope, Check Out the updated jsFiddles above

#MZetko I understand and respect your desire to implement it on your on.
#apaul34208 pointed in the right direction when he suggested Isotope. That's the term used for this kind of layout grid. You don't have to use jQuery, but it would be useful to look at how it does what it does to get it done... :)
I'm currently implementing a Wordpress site with the Studiofolio template, and even though I think it would have been fun to do it myself, I'm happy I spent those bucks on it. Now I can finish setting it up and go on to the next project. Cheers!

1) Loading images
You should hide images by default. You can do this by setting their dimensions to 1px
(using display:none may cause loading troubles). At the end of your css:
div.tile img { width:1px; height:1px }
This will be overwritten by your tile specific styles on a per element basis after your calculations are done.
To have a background while they are loading you have to use a background color other than white :-)
(e.g. look at your div.wide-tile rule). At the end of your css:
.col .tile { background-color: #2440b2; }
This will have a greater specificity than your white backgrounds so it will override them.
To avoid flicker I would hide all the tiles until their initial position is know (I didn't modify your js).
[working demo] (make sure to use an empty cache)
2) Reisizing with animation
Basically you have to give up using floats for this to work and use absolutely positioned elements instead (floats cannot be animated).
After this you can simply use CSS transitions on the tiles (top, left) so when you recalculate their positions inside a resize event handler they will slide to their new positions with a nice animation.
-webkit-transition: left .5s, top .5s;
-moz-transition: left .5s, top .5s;
transition: left .5s, top .5s;
[working demo]

Related

JavaScript Css Animation

I have a Javascript animation at http://dev17.edreamz3.com/css/
All code works, however, there are performance problems. on Desktop, its good, On mobile things are so slow that it's unusable. I want to optimize the animation so that it runs smoothly on mobile. It can take 20 seconds or more for the animation to render.
Right now the way the code is designed is in js/anim.js there is a render() function that gets executed every time a scroll event happens. The problem is that this routine is not efficient, that's what I think of. Each time render() executes it loops through all the paths and sections of the maze and redraws them, is there any alternative way or a strategy to get it working both on mobile as well as desktop.
var offPathTime = 1000;
window.offSection = -1;
function render() {
// var top = ($window.scrollTop() + (0.4 * $window.height())) / window.scale;
var top = ($('.parent-div').scrollTop() + (0.4 * $('.parent-div').height())) / window.scale;
top -= 660;
top /= mazeSize.h;
if (window.offSection != -1) {
$body.addClass("blockScroll");
$('.parent-div').addClass("blockScroll");
// var wtop = $window.scrollTop() / window.scale;
var wtop = $('.parent-div').scrollTop() / window.scale;
wtop -= 660;
wtop /= mazeSize.h;
var $offSection = $("#offSection" + window.offSection);
var $section = $("#section" + window.offSection);
$(".section").removeClass("sectionActive");
$offSection.addClass("sectionActive");
$section.addClass("sectionActive");
var sTop = 200 -(mazeSize.h * (window.offSections[window.offSection].cy - wtop));
$container.animate({
left: 290 -(mazeSize.w * window.offSections[window.offSection].cx) + "px",
top: sTop + "px"
}, offPathTime);
// Path
var lr = offPaths[window.offSection].x1 > offPaths[window.offSection].x0;
var dx = Math.abs(offPaths[window.offSection].x1 - offPaths[window.offSection].x0);
var dashw = (dx * mazeSize.w) | 0;
$offPaths[window.offSection].css("width", "0px");
$offPaths[window.offSection].show();
if (lr) {
$offPaths[window.offSection].animate({
width: dashw + "px"
}, offPathTime);
} else {
var x0 = offPaths[window.offSection].x0 * mazeSize.w;
var x1 = offPaths[window.offSection].x1 * mazeSize.w;
$offPaths[window.offSection].css("left", x0 + "px");
$offPaths[window.offSection].animate({
width: dashw + "px",
left: x1 + "px"
}, offPathTime);
}
return;
}
$body.removeClass("blockScroll");
$('.parent-div').removeClass("blockScroll");
$(".offPath").hide();
if ($container.css("top") != "0px") {
$container.animate({
left: "-1550px",
top: "0px"
}, 500);
}
var pathIdx = -1;
var path0 = paths[0];
var path1;
var inPath = 0;
var i;
var curTop = 0;
var found = false;
for (i=0; i<paths.length; i++) {
var top0 = (i == 0) ? 0 : paths[i-1].y;
var top1 = paths[i].y;
if (top >= top0 && top < top1) {
pathIdx = i;
path1 = paths[i];
inPath = (top - top0) / (top1 - top0);
found = true;
if (i > 0) {
var dy = paths[i].y - paths[i-1].y;
var dx = paths[i].x - paths[i-1].x;
var vert = dx == 0;
if (vert)
$paths[i-1].css("height", (dy * mazeSize.h * inPath) + "px");
$paths[i-1].show();
}
} else if (top >= top0) {
path0 = paths[i];
var dy = paths[i].y - top0;
var vert = dy != 0;
if (i > 0) {
if (vert)
$paths[i-1].css("height", (dy * mazeSize.h) + "px");
$paths[i-1].show();
}
} else {
if (i > 0) {
$paths[i-1].hide();
}
}
curTop = top1;
}
// Check for an active section
$(".section").removeClass("sectionActive");
var section;
for (i=0; i<sections.length; i++) {
var d = Math.abs(sections[i].cy - (top - 0.05));
if (d < 0.07) {
var $section = $("#section" + i);
$section.addClass("sectionActive");
}
}
}
1) At the very least - assign all DOM objects to variables outside of the function scope. Like this:
var $parentDiv = $('.parent-div');
var $sections = $(".section");
...
function render() {
...
2) Also you should probably stop animation before executing it again, like this:
$container.stop(true).animate({
...
If you are running render() function on scroll - it will run many times per second. stop() helps to prevent it somewhat.
3) If it will not be sufficient - you can switch from jQuery to Zepto(jQuery-like api, but much faster and uses css transitions for animations) or to Velocity(basically drop-in replacement for jQuery $.animate and much faster than original) or even to GSAP - much more work obviously, but it is very fast and featured animation library.

What's best way to run same function on multiple elements only when they're inside viewport?

I have 3 elements with background images that I want to scale from x to 1. I want it to begin when the top of the element is just inside the viewport (this may vary a little).
I have achieved this effect the long way:
function animatePanelBackgrounds() {
var $toolsBG = $('#js-tools-bg'),
$dennysBG = $('#js-dennys-bg'),
$verizonBG = $('#js-verizon-bg'),
$llbeanBG = $('#js-llbean-bg');
var dennysTop = Math.floor( $("#js-dennys").offset().top );
var dennysGo = dennysTop - window.innerHeight;
var llbeanTop = Math.floor( $("#js-llbean").offset().top );
var llbeanGo = llbeanTop - window.innerHeight;
var verizonTop = Math.floor( $("#js-verizon").offset().top );
var verizonGo = verizonTop - window.innerHeight;
var toolsTop = Math.floor($toolsBG.offset().top);
var toolsGo = 0;
var ratio, $that;
if ( thisWindows.offsetY() >= toolsGo ) {
ratio = toolsTop/(thisWindows.offsetY()*10);
$that = $toolsBG;
$that.css({
"transform": "scale(" + (1.0 + thisWindows.offsetY()*.0002) + ")",
"-webkit-transform": "scale(" + (1.0 + thisWindows.offsetY()*.0002) + ")",
"-moz-transform": "scale(" + (1.0 + thisWindows.offsetY()*.0002) + ")"
})
}
if ( thisWindows.offsetY() >= dennysGo ) {
ratio = dennysTop/thisWindows.offsetY()*.8;
$that = $dennysBG;
if ( ratio <= 1 ) {
$that.css({
"transform": "scale(1)",
"-webkit-transform": "scale(1)",
"-moz-transform": "scale(1)"
})
} else {
$that.css({
"transform": "scale(" + ratio + ")",
"-webkit-transform": "scale(" + ratio + ")",
"-moz-transform": "scale(" + ratio + ")"
})
}
}
if ( thisWindows.offsetY() >= verizonGo ) {
ratio = verizonTop/thisWindows.offsetY()*.8;
$that = $verizonBG;
if ( ratio <= 1 ) {
$that.css({
"transform": "scale(1)",
"-webkit-transform": "scale(1)",
"-moz-transform": "scale(1)"
})
} else {
$that.css({
"transform": "scale(" + ratio + ")",
"-webkit-transform": "scale(" + ratio + ")",
"-moz-transform": "scale(" + ratio + ")"
})
}
}
if ( thisWindows.offsetY() >= llbeanGo ) {
ratio = llbeanTop/thisWindows.offsetY()*.8;
$that = $llbeanBG;
if ( ratio <= 1 ) {
$that.css({
"transform": "scale(1)",
"-webkit-transform": "scale(1)",
"-moz-transform": "scale(1)"
})
} else {
$that.css({
"transform": "scale(" + ratio + ")",
"-webkit-transform": "scale(" + ratio + ")",
"-moz-transform": "scale(" + ratio + ")"
})
}
}
}
$(window).on('scroll', function() {
animatePanelBackgrounds();
}
I have also achieved this with a function that take a couple simple parameters:
function scaleBackground(element, multiplier) {
var $el = $(element),
elTop = Math.floor( $el.offset().top),
startPosition = elTop - window.innerHeight;
$win.on('scroll', function() {
if(thisWindows.offsetY() >= startPosition) {
var ratio = elTop/thisWindows.offsetY()*multiplier;
if ( ratio <= 1 ) {
$el.css({
"transform": "scale(1)",
"-webkit-transform": "scale(1)",
"-moz-transform": "scale(1)"
})
} else {
$el.css({
"transform": "scale(" + ratio + ")",
"-webkit-transform": "scale(" + ratio + ")",
"-moz-transform": "scale(" + ratio + ")"
})
}
}
})
}
scaleBackground('#js-dennys-bg', '.8');
scaleBackground('#js-llbean-bg', '.8');
scaleBackground('#js-verizon-bg', '.8');
I feel like this should be handled in a loop of some sorts, but I haven't had any luck. Here's my basic attempt, I've tried tweaking little things in it along the way with 0 success:
var panels = $('.panel__bg');
for ( i = 0; i < panels.length; i++ ) {
var $that = $(panels[i]),
begin = $that.offset().top;
if ( begin <= window.scrollY ) {
var ratio = begin/(window.scrollY * 10);
if ( ratio <= 1 ) {
$that.css({
"transform": "scale(1)",
"-webkit-transform": "scale(1)",
"-moz-transform": "scale(1)"
})
} else {
$that.css({
"transform": "scale(" + ratio + ")",
"-webkit-transform": "scale(" + ratio + ")",
"-moz-transform": "scale(" + ratio + ")"
})
}
}
}
My question, finally, is simply: What is the best way to do this. By "best way", I am extremely concerned with performance and secondly concerned with readability/fewest lines of code.
Here is some critique for your code. It's untested, but hopefully it addresses some of your concerns.
// .each is easier to understand, and cleaner looking than a for loop
$('.panel__bg').each(function(i, panel){
// name this something that makes more sense than "$that", e.g. "$panel"
var $panel = $(panel),
begin = $panel.offset().top;
if ( begin <= window.scrollY ) {
// caps to ratio=1. no need for if/else block
var ratio = Math.min(1, begin/(window.scrollY * 10));
// on SO, it helps to only show code relevant to the issue
$panel.css({"transform": "scale(" + ratio + ")" });
}
});
I assume this code is being run every time the scroll event is fired. You might run into trouble on ios because js execution is blocked during scroll. See this issue.
Not sure if this is really THE BEST way to do it, but here are some of the things I would do:
1 - as suggested already, using CSS and toggle class is probably better than using jQuery CSS method. And since all your elements share same styles instead of IDs you can use common class (as you already did in second snippet), so we have something like this:
.panel__bg {
transform: scale(0.8);
}
.panel__bg.is-visible {
transform: scale(1);
}
2 - This is small jQuery plugin used to check elements visibility:
(function($) {
/**
* Copyright 2012, Digital Fusion
* Licensed under the MIT license.
* http://teamdf.com/jquery-plugins/license/
*
* #author Sam Sehnert
* #desc A small plugin that checks whether elements are within
* the user visible viewport of a web browser.
* only accounts for vertical position, not horizontal.
*/
$.fn.visible = function(partial) {
var $t = $(this),
$w = $(window),
viewTop = $w.scrollTop(),
viewBottom = viewTop + $w.height(),
_top = $t.offset().top,
_bottom = _top + $t.height(),
// if partial === false, visible will be true when 100% of element is shown
compareTop = partial === true ? _bottom : _top,
compareBottom = partial === true ? _top : _bottom;
return ((compareBottom <= viewBottom) && (compareTop >= viewTop));
};
})(jQuery);
3 - since you are listening for scroll events you should probably look into requestAnimationFrame and include this polyfill if you need support for IE9 or less and Android 4.3 or less.
(function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame']
|| window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}());
4 - utilizing rAF you can optimize scroll events or even avoid them. I didn't test for performance difference between two linked examples, but I choose latter for brevity
5 - finally, your scaleBackground function is now basically just class toggler thingy that accepts element class and modifier class
(parts 4 & 5 are wrapped inside IIFE to avoid global variables)
(function() {
var scaleBackground = function(element, triggerClass) {
var $element = $(element);
$element.each(function(i, el) {
var el = $(el);
// check if it's shown
if (!el.hasClass(triggerClass) && el.visible(true)) {
el.addClass(triggerClass);
}
});
};
var lastPosition = -1;
var loop = function() {
// Avoid calculations if not needed
if (lastPosition == window.pageYOffset) {
requestAnimationFrame(loop);
return false;
} else {
lastPosition = window.pageYOffset;
}
// do stuff you need to do
scaleBackground(".panel__bg", "is-visible");
requestAnimationFrame(loop);
};
loop();
})();
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
// http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
// requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel
// MIT license
(function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame']
|| window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
})();
(function($) {
/**
* Copyright 2012, Digital Fusion
* Licensed under the MIT license.
* http://teamdf.com/jquery-plugins/license/
*
* #author Sam Sehnert
* #desc A small plugin that checks whether elements are within
* the user visible viewport of a web browser.
* only accounts for vertical position, not horizontal.
*/
$.fn.visible = function(partial) {
var $t = $(this),
$w = $(window),
viewTop = $w.scrollTop(),
viewBottom = viewTop + $w.height(),
_top = $t.offset().top,
_bottom = _top + $t.height(),
// if partial === false, visible will be true when 100% of element is shown
compareTop = partial === true ? _bottom : _top,
compareBottom = partial === true ? _top : _bottom;
return ((compareBottom <= viewBottom) && (compareTop >= viewTop));
};
})(jQuery);
(function() {
var scaleBackground = function(element, triggerClass) {
var $element = $(element);
$element.each(function(i, el) {
var el = $(el);
// check if it's shown
if (!el.hasClass(triggerClass) && el.visible(true)) {
el.addClass(triggerClass);
}
});
};
var lastPosition = -1;
var loop = function() {
// Avoid calculations if not needed
if (lastPosition == window.pageYOffset) {
requestAnimationFrame(loop);
return false;
} else {
lastPosition = window.pageYOffset;
}
// do stuff you need to do
scaleBackground(".panel__bg", "is-visible");
requestAnimationFrame(loop);
};
loop();
})();
.panel__bg {
transform: scale(0.8);
transition: transform .3s ease;
width: 200px;
height: 200px;
position: absolute;
background: hotpink;
}
.panel__bg.is-visible {
transform: scale(1);
}
.one { top: 800px; }
.two { top: 1600px; }
.three { top: 3200px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel__bg one">test 1</div>
<div class="panel__bg two">test 2</div>
<div class="panel__bg three">test 3</div>
references:
http://codepen.io/chriscoyier/pen/DjmJe
https://css-tricks.com/using-requestanimationframe/
https://gist.github.com/paulirish/1579671
http://www.html5rocks.com/en/tutorials/speed/animations/
https://gist.github.com/Warry/4254579
codepen demo

DIVs to randomly fadeIn on page

Okay, I've seen a few things that sort of * answer my question, but none of them quite do what I want to do / I'd like to understand how to do this myself from start to finish as a learning exercise. I'm a novice at all this, so bear with me!
What I'm Trying to Do:
I have a black page and I'd like 20-30 small, white div boxes to fadeIn at random positions on the page (like stars is sort of the vibe I'm going for).
Ideally, they wouldn't overlap and they would be randomly sized between 5px and 10px, but I recognize that this might be getting a little too complicated.
Here's what I have so far
I've been working off this jsfiddle and well as this one. This is what I've come up with (that doesn't work, they all fade in equally spaced in a line and don't stay confined from to the site)
Here's my jsfiddle, code below
function randomPosition() {
var h = $(window).height()-10;
var w = $(window).width()-10;
var newHeight = Math.floor(Math.random() * h);
var newWidth = Math.floor(Math.random() * w);
return [newHeight, newWidth];
}
$(document).ready(function() {
var newPosition = randomPosition();
$('.star').css( {
'margin-left':newPosition[1]+'px',
'margin-top':newPosition[0]+'px'
}).each(function(index) { $(this).delay(1500*index).fadeIn('slow');
})
});
CSS
body {
background-color: black;
}
.star {
height: 10px;
width: 10px;
background-color: white;
display: none;
}
HTML (is there a way to do this with just a for loop or something similar?)
<div class="star"> </div>
<div class="star"> </div>
<div class="star"> </div>
<div class="star"></div>
The sizing and positioning isn't too hard. The thing is to do it all in the each loop - currently you get 1 position and use it for everything. Also you will want to make them position:absolute so they don't go off the page.
I've updated your fiddle to set the random position and a size between 5 and 10px:
The overlapping is a bit harder. You need to keep track of the sizes and positions you have generated and in the same .each function compare the current generated size+position to the previous ones to check for overlapping.
http://jsfiddle.net/5ocb5aww/3/
function randomPosition() {
var h = $(window).height()-10;
var w = $(window).width()-10;
var newHeight = Math.floor(Math.random() * h);
var newWidth = Math.floor(Math.random() * w);
return [newHeight, newWidth];
}
function randomSize() {
return Math.round(Math.random() * 5) + 5;
}
$(document).ready(function() {
// stores generated star positions
var stars = [];
$('.star').each(function(index) {
var newPosition, newSize;
// check for overlap
var isOverlap = true;
while(isOverlap)
{
newPosition = randomPosition();
newSize = randomSize();
// check previous stars to see if an edge of this one overlaps
isOverlap = $.grep(stars, function(s) {
return (
(newPosition[1] >= s.x1 && newPosition[1] <= s.x2)
|| (newPosition[1]+newSize >= s.x1 && newPosition[1]+newSize <= s.x2)
)
&& (
(newPosition[0] >= s.y1 && newPosition[0] <= s.y2)
|| (newPosition[0]+newSize >= s.y1 && newPosition[0]+newSize <= s.y2)
);
}).length > 0;
}
// store to check later stars against it
stars.push({
x1: newPosition[1],
x2: newPosition[1] + newSize,
y1: newPosition[0],
y2: newPosition[0] + newSize,
size: newSize});
$(this).css({
'margin-left':newPosition[1]+'px',
'margin-top':newPosition[0]+'px',
'width':newSize + 'px',
'height':newSize + 'px'
});
$(this).delay(800*index).fadeIn('slow');
})
});
Here is my approach to your exercise ... the overlapping position would require a little bit more effort ... I'll leave you that to sort for yourself (may require restructuring the code I'm handing here)
jsFiddle Demo
JS
function starDust(wdt, hgt, tSt, tAp){
var timer = tAp * 1000;
var defInt = tSt,
starInt = setInterval(function(){
var posX = Math.floor((Math.random() * wdt) + 1),
posY = Math.floor((Math.random() * hgt) + 1),
size = Math.floor((Math.random() * 10) + 1);
$('body').append('<div class="star"></div>');
$('.star:last').css({'width':size,'height':size,'left':posX,'top':posY}).hide().fadeIn('slow');
var totalStars = $('.star').length;
if(totalStars == defInt){
clearInterval(starInt);
}
}, timer);
}
$(function(){
// Function arguments: starDust(max X position in px, max Y position in px, total number of stars, time in seconds between stars show);
starDust(600,300,25,1);
});
CSS
body{
background-color:#000;
}
.star{
position: absolute;
background-color:#fff;
min-width:5px;
min-height:5px;
}

Adapt random image placement code for flexible layout

I'm looking for an effect very similar to this:
http://jsfiddle.net/G5Xrz/
function rnd(max) { return Math.floor(Math.random()*(max+1)) }
function showImage(container, maxwidth, maxheight, imgsrc, imgwidth, imgheight) {
var id = "newimage" + rnd(1000000);
$(container).append(
"<img id='" + id + "' src='" + imgsrc +
"' style='display:block; float:left; position:absolute;" +
"left:" + rnd(maxwidth - imgwidth) + "px;" +
"top:" + rnd(maxheight - imgheight) + "px'>");
$('#' + id).fadeIn();
return id;
}
setInterval(
function() {
showImage("#container", 400, 600,
"http://placekitten.com/" + (90 + rnd(10)) + "/" + (90 + rnd(10)),
100, 100);
}, 700);
But i'd prefer a flexible layout, ie images not bound by a div with predefined height and width, instead responding to the dimensions of the browser.
The following piece of code seems to have a more appropriate way of generating the random positions:
http://jsfiddle.net/Xw29r/15/
function makeNewPosition(){
// Get viewport dimensions (remove the dimension of the div)
var h = $(window).height() - 50;
var w = $(window).width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh,nw];
}
function animateDiv(){
var newq = makeNewPosition();
var oldq = $('.a').offset();
var speed = calcSpeed([oldq.top, oldq.left], newq);
$('.a').animate({ top: newq[0], left: newq[1] }, speed, function(){
animateDiv();
});
};
However I'm very much a beginner with javascript and I don't know how to combine the two.
Can anyone help?
Thanks
Take this part from the second code:
// Get viewport dimensions (remove the dimension of the div)
var h = $(window).height() - 50;
var w = $(window).width() - 50;
and use those variables h and w with the browser height and width (minus 50) as the appropriate parameters in this part of the first code:
setInterval(
function() {
showImage("#container", 400, 600,
"http://placekitten.com/" + (90 + rnd(10)) + "/" + (90 + rnd(10)),
100, 100);
}, 700);
Also, the first code has this HTML:
<div id="container" style="width:400px; height:600px; background: green; position:relative"></div>
That hard-codes the height and width at pixel values. You can use a CSS percentage value to make the width respond to the parent container's size. However, you will need JS to set the height properly; a percentage for the height does nothing
Putting that all together (and removing the "minus 50" part), you get this:
jsFiddle demo
<div id="container" style="width:100%; height:100px; background: green; position:relative"></div>
function adjustContainerHeight(height) {
$('#container').height(height);
}
adjustContainerHeight($(window).height());
setInterval(
function() {
var h = $(window).height();
var w = $(window).width();
adjustContainerHeight(h);
showImage("#container", w, h,
"http://placekitten.com/" + (90 + rnd(10)) + "/" + (90 + rnd(10)),
100, 100);
}, 700);
This updates the height of the container when the page is first loaded, and once again whenever the random image is placed. More robust code would have a separate height-adjusting event handler that updates the height whenever the page size changes.

random position of divs in javascript

I'm trying to make Divs to appear randomly anywhere on a webpage with javascript. So a div appears then disappears, then another div appears somewhere else on the page then disappears, then another div appears again in another random spot on the page then disappears, and so on.
I'm not sure on how to generate random units in pixels or what technique to use to generate random positions.
How do I do that? Here's my code:
var currentDivPosition = myDiv.offset(),
myDivWidth = myDiv.width(),
myDivHeight = myDiv.height(),
var myDiv = $('<div>'),
finalDivPositionTop, finalDivPositionLeft;
myDiv.attr({ id: 'myDivId', class: 'myDivClass' }); // already defined with position: absolute is CSS file.
// Set new position
finalDivPositionTop = currentDivPosition.top + Math.floor( Math.random() * 100 );
finalDivPositionLeft = currentDivPosition.left + Math.floor( Math.random() * 100 );
myDiv.css({ // Set div position
top: finalDivPositionTop,
left: finalDivPositionLeft
});
$('body').append(myDiv);
myDiv.text('My position is: ' + finalDivPositionTop + ', ' + finalDivPositionLeft);
myDiv.fadeIn(500);
setTimeout(function(){
myDiv.fadeOut(500);
myDiv.remove();
}, 3000);
Here's one way to do it. I'm randomly varying the size of the div within a fixed range, then setting the position so the object is always placed within the current window boundaries.
(function makeDiv(){
// vary size for fun
var divsize = ((Math.random()*100) + 50).toFixed();
var color = '#'+ Math.round(0xffffff * Math.random()).toString(16);
$newdiv = $('<div/>').css({
'width':divsize+'px',
'height':divsize+'px',
'background-color': color
});
// make position sensitive to size and document's width
var posx = (Math.random() * ($(document).width() - divsize)).toFixed();
var posy = (Math.random() * ($(document).height() - divsize)).toFixed();
$newdiv.css({
'position':'absolute',
'left':posx+'px',
'top':posy+'px',
'display':'none'
}).appendTo( 'body' ).fadeIn(100).delay(1000).fadeOut(500, function(){
$(this).remove();
makeDiv();
});
})();
Edit: For fun, added a random color.
Edit: Added .remove() so we don't pollute the page with old divs.
Example: http://jsfiddle.net/redler/QcUPk/8/
Let's say you have this HTML:
<div id="test">test div</div>
And this CSS:
#test {
position:absolute;
width:100px;
height:70px;
background-color:#d2fcd9;
}
Using jQuery, if you use this script, whenever you click the div, it will position itself randomly in the document:
$('#test').click(function() {
var docHeight = $(document).height(),
docWidth = $(document).width(),
$div = $('#test'),
divWidth = $div.width(),
divHeight = $div.height(),
heightMax = docHeight - divHeight,
widthMax = docWidth - divWidth;
$div.css({
left: Math.floor( Math.random() * widthMax ),
top: Math.floor( Math.random() * heightMax )
});
});
The way this works is...first you calculate the document width and height, then you calculate the div width and height, and then you subtract the div width from the document width and the div height from the document height and consider that the pixel range you're willing to put the div in (so it doesn't overflow out of the document). If you have padding and border on the div, you'll need to account for those values too. Once you've figured out the range, you can easily multiple that by Math.random() and find the random position of your div.
So once more: first find the dimensions of the container, then find the dimensions of your element, then subtract element dimensions from container dimensions, and THEN use Math.random() on that value.
The basic idea is encapsulated here:
http://jsfiddle.net/5mvKE/
Some bugs:
You missed to position the div absolutely. Otherwise it will not
work.
I think you need to ad 'px' to the numbers.
The map is made of strings
Right in your jQuery css setup:
myDiv.css({
'position' : 'absolute',
'top' : finalDivPositionTop + 'px',
'left' : finalDivPositionLeft + 'px'
});
I changed an existant code by this one for our website, you can see it on tweefox.nc
<script>
function draw() {
$(canvas).attr('width', WIDTH).attr('height',HEIGHT);
con.clearRect(0,0,WIDTH,HEIGHT);
for(var i = 0; i < pxs.length; i++) {
pxs[i].fade();
pxs[i].move();
pxs[i].draw();
}
}
function Circle() {
this.s = {ttl:8000, xmax:10, ymax:4, rmax:10, rt:1, xdef:950, ydef:425, xdrift:4, ydrift: 4, random:true, blink:true};
this.reset = function() {
this.x = (this.s.random ? WIDTH*Math.random() : this.s.xdef);
this.y = (this.s.random ? HEIGHT*Math.random() : this.s.ydef);
this.r = ((this.s.rmax-1)*Math.random()) + 1;
this.dx = (Math.random()*this.s.xmax) * (Math.random() < .5 ? -1 : 1);
this.dy = (Math.random()*this.s.ymax) * (Math.random() < .5 ? -1 : 1);
this.hl = (this.s.ttl/rint)*(this.r/this.s.rmax);
this.rt = Math.random()*this.hl;
this.s.rt = Math.random()+1;
this.stop = Math.random()*.2+.4;
this.s.xdrift *= Math.random() * (Math.random() < .5 ? -1 : 1);
this.s.ydrift *= Math.random() * (Math.random() < .5 ? -1 : 1);
}
this.fade = function() {
this.rt += this.s.rt;
}
this.draw = function() {
if(this.s.blink && (this.rt <= 0 || this.rt >= this.hl)) {
this.s.rt = this.s.rt*-1;
this.dx = (Math.random()*this.s.xmax) * (Math.random() < .5 ? -1 : 1);
this.dy = (Math.random()*this.s.ymax) * (Math.random() < .5 ? -1 : 1);
} else if(this.rt >= this.hl) this.reset();
var newo = 1-(this.rt/this.hl);
con.beginPath();
con.arc(this.x,this.y,this.r,0,Math.PI*2,true);
con.closePath();
var cr = this.r*newo;
g = con.createRadialGradient(this.x,this.y,0,this.x,this.y,(cr <= 0 ? 1 : cr));
g.addColorStop(0.0, 'rgba(255,255,255,'+newo+')');
g.addColorStop(this.stop, 'rgba(255,255,255,'+(newo*.2)+')');
g.addColorStop(1.0, 'rgba(255,255,255,0)');
con.fillStyle = g;
con.fill();
}
this.move = function() {
this.x += (this.rt/this.hl)*this.dx;
this.y += (this.rt/this.hl)*this.dy;
if(this.x > WIDTH || this.x < 0) this.dx *= -1;
if(this.y > HEIGHT || this.y < 0) this.dy *= -1;
}
this.getX = function() { return this.x; }
this.getY = function() { return this.y; }
}
$(document).ready(function(){
// if( /Android|AppleWebKit|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
// } else {
if(document.getElementById('pixie')) {
WIDTH = $(window).width();
HEIGHT = $(window).height();
canvas = document.getElementById('pixie');
$(canvas).attr('width', WIDTH).attr('height',HEIGHT);
con = canvas.getContext('2d');
pxs = new Array();
rint = 60;
for(var i = 0; i < 50; i++) {
pxs[i] = new Circle();
pxs[i].reset();
}
setInterval(draw,rint);
}
// }
});
</script>

Categories