Depending on the width of the screen the JavaScript animates a node and then loops another animation.
I'm trying to understand DRY but my JavaScript skills aren't quite up to scratch to get this code as optimised as possible. I'm also wanting to implement $(window).resize(function() { });
to detect this change without a refresh. Is using constants the best way to optimise this code? If so, how would this be achieved?
'use strict';
/*jslint browser: true*/
/*global $, jQuery*/
/*
--------------------------------------------------------
VARIABLES
--------------------------------------------------------
*/
var width = $(window).width(), // window width
down_dur,
left_dur,
up_dur,
right_dur;
/*
--------------------------------------------------------
FUNCTION CODE TO BE EXECUTED
--------------------------------------------------------
*/
function animate_node(down, down_dur, left, left_dur, up, up_dur, right, right_dur) {
down = down + 'px';
left = left + 'px';
up = up + 'px';
right = right + 'px';
$('.node')
.animate({top: down},
{ duration: down_dur, easing : 'linear', queue: true })
.animate({marginLeft: left},
{ duration: left_dur, easing : 'linear', queue: true })
.animate({top: up},
{ duration: up_dur, easing : 'linear', queue: true })
.animate({marginLeft: right},
{ duration: right_dur, easing : 'linear', queue: true });
}
/*
--------------------------------------------------------
CALL THE FUNCTIONS
--------------------------------------------------------
*/
// fire the following when the dom is ready
$(function () {
if (width > 840) {
$('.node').each(function(i) {
$(this).delay(1500 * (i + 1))
.animate({top: '157px'},
{ duration: 1000, easing : 'linear', queue: true })
.animate({marginLeft: '264px'},
{ duration: 1000, easing : 'linear', queue: true });
});
animate_node(425, 2000, -284, 2000, 157, 2000, 264, 2000);
setInterval(function() {
animate_node(425, 2000, -284, 2000, 157, 2000, 264, 2000);
}, 2000);
} else if (width < 840 && width > 600) {
$('.node').each(function(i) {
$(this).delay(1500 * (i + 1))
.animate({top: '165px'},
{ duration: 1000, easing : 'linear', queue: true })
.animate({marginLeft: '179px'},
{ duration: 1000, easing : 'linear', queue: true });
});
animate_node(490, 2000, -199, 2000, 165, 2000, 179, 2000);
setInterval(function() {
animate_node(490, 2000, -199, 2000, 165, 2000, 179, 2000);
}, 2000);
} else if ((!(document.documentElement.hasOwnProperty('ontouchstart'))) &&
width < 600) {
$('.node').each(function(i) {
$(this).delay(1833.333 * (i + 1));
});
animate_node(1095, 5000, 102, 500, 165, 5000, -9, 500);
setInterval(function() {
animate_node(1095, 5000, 102, 500, 165, 5000, -9, 500);
}, 2000);
}
});