JS: cannot read this.data() in jquery event - javascript

I'm kinda new to JS so this may be pretty easy to solve.
I simply want to change interactive map elements' opacity and color when mouse enters element and change it back when it leaves.
So this is what I'm doing:
var paper = Raphael('map', '100%', '100%');
// map contents
var rect = paper.rect(3.5714281, 74.505051, 151.42857, 143.57143).attr({
x: '3.5714281',
y: '74.505051',
fill: '#ffb380',
stroke: '#ff6600',
'stroke-width': '1',
'stroke-opacity': '1'
}).transform("t6.9285719,8.1378246").data('id', 'rect');
var crcl = paper.path("m 472.14285,202.00504 a 72.5,72.5 0 1 1 -145,0 72.5,72.5 0 1 1 145,0 z").attr({
fill: '#916f6f',
stroke: '#6c5353',
'stroke-width': '1',
'stroke-opacity': '1'
}).transform("t6.9285719,8.1378246 t-245,-127.14286").data('id', 'crcl');
var objs = [];
objs.push(rect, crcl);
for (var i = objs.length - 1; i >= 0; i--) {
objs[i].data('original-fill', objs[i].data('fill'));
objs[i].mouseover(function(event) {
damn = this.data('fill');
this.stop(true, false).animate({
opacity: 0.7,
fill: 'white',
},
75);
});
objs[i].mouseout(function(event) {
this.stop(true, false).animate({
opacity: 1,
fill: this.data('original-fill'),
},
200);
});
};
But every time i move mouse out it sets to 'none' like this.data('original-fill') was unset. Though I can access objs[i].data('original-fill') outside mouseover and mouseout.
I'm using Raphaël JS library.
I would appreciate any help.

If CSS is in your arsenal for the project, it offers a transition property and a :hover attribute to animate styles over a length of time on mouseover events. If CSS is something you're able to use, this can accomplish what you're outlining in your expected behavior (just replace div with a class on the elements you're looking to animate):
div {
opacity: 1;
background-color: #000;
transition: opacity .2s;
transition: background-color .2s;
}
div:hover {
background-color: #FFF;
opacity: .7;
}
It's not a javascript solution, but is considerably more elegant if your hover needs are strictly style-related

Related

jquery animate body background color not working [duplicate]

I am trying to animate a change in backgroundColor using jQuery on mouseover.
I have checked some example and I seem to have it right, it works with other properties like fontSize, but with backgroundColor I get and "Invalid Property" js error.
The element I am working with is a div.
$(".usercontent").mouseover(function() {
$(this).animate({ backgroundColor: "olive" }, "slow");
});
Any ideas?
The color plugin is only 4kb so much cheaper than the UI library. Of course you'll want to use a decent version of the plugin and not some buggy old thing which doesn't handle Safari and crashes when the transitions are too fast. Since a minified version isn't supplied you might like test various compressors and make your own min version. YUI gets the best compression in this case needing only 2317 bytes and since it is so small - here it is:
(function (d) {
d.each(["backgroundColor", "borderBottomColor", "borderLeftColor", "borderRightColor", "borderTopColor", "color", "outlineColor"], function (f, e) {
d.fx.step[e] = function (g) {
if (!g.colorInit) {
g.start = c(g.elem, e);
g.end = b(g.end);
g.colorInit = true
}
g.elem.style[e] = "rgb(" + [Math.max(Math.min(parseInt((g.pos * (g.end[0] - g.start[0])) + g.start[0]), 255), 0), Math.max(Math.min(parseInt((g.pos * (g.end[1] - g.start[1])) + g.start[1]), 255), 0), Math.max(Math.min(parseInt((g.pos * (g.end[2] - g.start[2])) + g.start[2]), 255), 0)].join(",") + ")"
}
});
function b(f) {
var e;
if (f && f.constructor == Array && f.length == 3) {
return f
}
if (e = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(f)) {
return [parseInt(e[1]), parseInt(e[2]), parseInt(e[3])]
}
if (e = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(f)) {
return [parseFloat(e[1]) * 2.55, parseFloat(e[2]) * 2.55, parseFloat(e[3]) * 2.55]
}
if (e = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(f)) {
return [parseInt(e[1], 16), parseInt(e[2], 16), parseInt(e[3], 16)]
}
if (e = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(f)) {
return [parseInt(e[1] + e[1], 16), parseInt(e[2] + e[2], 16), parseInt(e[3] + e[3], 16)]
}
if (e = /rgba\(0, 0, 0, 0\)/.exec(f)) {
return a.transparent
}
return a[d.trim(f).toLowerCase()]
}
function c(g, e) {
var f;
do {
f = d.css(g, e);
if (f != "" && f != "transparent" || d.nodeName(g, "body")) {
break
}
e = "backgroundColor"
} while (g = g.parentNode);
return b(f)
}
var a = {
aqua: [0, 255, 255],
azure: [240, 255, 255],
beige: [245, 245, 220],
black: [0, 0, 0],
blue: [0, 0, 255],
brown: [165, 42, 42],
cyan: [0, 255, 255],
darkblue: [0, 0, 139],
darkcyan: [0, 139, 139],
darkgrey: [169, 169, 169],
darkgreen: [0, 100, 0],
darkkhaki: [189, 183, 107],
darkmagenta: [139, 0, 139],
darkolivegreen: [85, 107, 47],
darkorange: [255, 140, 0],
darkorchid: [153, 50, 204],
darkred: [139, 0, 0],
darksalmon: [233, 150, 122],
darkviolet: [148, 0, 211],
fuchsia: [255, 0, 255],
gold: [255, 215, 0],
green: [0, 128, 0],
indigo: [75, 0, 130],
khaki: [240, 230, 140],
lightblue: [173, 216, 230],
lightcyan: [224, 255, 255],
lightgreen: [144, 238, 144],
lightgrey: [211, 211, 211],
lightpink: [255, 182, 193],
lightyellow: [255, 255, 224],
lime: [0, 255, 0],
magenta: [255, 0, 255],
maroon: [128, 0, 0],
navy: [0, 0, 128],
olive: [128, 128, 0],
orange: [255, 165, 0],
pink: [255, 192, 203],
purple: [128, 0, 128],
violet: [128, 0, 128],
red: [255, 0, 0],
silver: [192, 192, 192],
white: [255, 255, 255],
yellow: [255, 255, 0],
transparent: [255, 255, 255]
}
})(jQuery);
I had the same problem and fixed it by including jQuery UI. Here is the complete script :
<!-- include Google's AJAX API loader -->
<script src="http://www.google.com/jsapi"></script>
<!-- load JQuery and UI from Google (need to use UI to animate colors) -->
<script type="text/javascript">
google.load("jqueryui", "1.5.2");
</script>
<script type="text/javascript">
$(document).ready(function() {
$('#menu ul li.item').hover(
function() {
$(this).stop().animate({backgroundColor:'#4E1402'}, 300);
}, function () {
$(this).stop().animate({backgroundColor:'#943D20'}, 100);
});
});
</script>
Do it with CSS3-Transitions. Support is great (all modern browsers, even IE). With Compass and SASS this is quickly done:
#foo {background:red; #include transition(background 1s)}
#foo:hover {background:yellow}
Pure CSS:
#foo {
background:red;
-webkit-transition:background 1s;
-moz-transition:background 1s;
-o-transition:background 1s;
transition:background 1s
}
#foo:hover {background:yellow}
I've wrote an german article about this topic: http://www.solife.cc/blog/animation-farben-css3-transition.html
Bitstorm has the best jquery color animation plugin I've seen. It's an improvement to the jquery color project. It also supports rgba.
http://www.bitstorm.org/jquery/color-animation/
You can use jQuery UI to add this functionality. You can grab just what you need, so if you want to animate color, all you have to include is the following code. I got if from latest jQuery UI (currently 1.8.14)
/******************************************************************************/
/****************************** COLOR ANIMATIONS ******************************/
/******************************************************************************/
// override the animation for color styles
$.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor',
'borderRightColor', 'borderTopColor', 'borderColor', 'color', 'outlineColor'],
function(i, attr) {
$.fx.step[attr] = function(fx) {
if (!fx.colorInit) {
fx.start = getColor(fx.elem, attr);
fx.end = getRGB(fx.end);
fx.colorInit = true;
}
fx.elem.style[attr] = 'rgb(' +
Math.max(Math.min(parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0], 10), 255), 0) + ',' +
Math.max(Math.min(parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1], 10), 255), 0) + ',' +
Math.max(Math.min(parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2], 10), 255), 0) + ')';
};
});
// Color Conversion functions from highlightFade
// By Blair Mitchelmore
// http://jquery.offput.ca/highlightFade/
// Parse strings looking for color tuples [255,255,255]
function getRGB(color) {
var result;
// Check if we're already dealing with an array of colors
if ( color && color.constructor == Array && color.length == 3 )
return color;
// Look for rgb(num,num,num)
if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
return [parseInt(result[1],10), parseInt(result[2],10), parseInt(result[3],10)];
// Look for rgb(num%,num%,num%)
if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];
// Look for #a0b1c2
if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];
// Look for #fff
if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];
// Look for rgba(0, 0, 0, 0) == transparent in Safari 3
if (result = /rgba\(0, 0, 0, 0\)/.exec(color))
return colors['transparent'];
// Otherwise, we're most likely dealing with a named color
return colors[$.trim(color).toLowerCase()];
}
function getColor(elem, attr) {
var color;
do {
color = $.curCSS(elem, attr);
// Keep going until we find an element that has color, or we hit the body
if ( color != '' && color != 'transparent' || $.nodeName(elem, "body") )
break;
attr = "backgroundColor";
} while ( elem = elem.parentNode );
return getRGB(color);
};
It's only 1.43kb after compressing with YUI:
$.each(["backgroundColor","borderBottomColor","borderLeftColor","borderRightColor","borderTopColor","borderColor","color","outlineColor"],function(b,a){$.fx.step[a]=function(c){if(!c.colorInit){c.start=getColor(c.elem,a);c.end=getRGB(c.end);c.colorInit=true}c.elem.style[a]="rgb("+Math.max(Math.min(parseInt((c.pos*(c.end[0]-c.start[0]))+c.start[0],10),255),0)+","+Math.max(Math.min(parseInt((c.pos*(c.end[1]-c.start[1]))+c.start[1],10),255),0)+","+Math.max(Math.min(parseInt((c.pos*(c.end[2]-c.start[2]))+c.start[2],10),255),0)+")"}});function getRGB(b){var a;if(b&&b.constructor==Array&&b.length==3){return b}if(a=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(b)){return[parseInt(a[1],10),parseInt(a[2],10),parseInt(a[3],10)]}if(a=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(b)){return[parseFloat(a[1])*2.55,parseFloat(a[2])*2.55,parseFloat(a[3])*2.55]}if(a=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(b)){return[parseInt(a[1],16),parseInt(a[2],16),parseInt(a[3],16)]}if(a=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(b)){return[parseInt(a[1]+a[1],16),parseInt(a[2]+a[2],16),parseInt(a[3]+a[3],16)]}if(a=/rgba\(0, 0, 0, 0\)/.exec(b)){return colors.transparent}return colors[$.trim(b).toLowerCase()]}function getColor(c,a){var b;do{b=$.curCSS(c,a);if(b!=""&&b!="transparent"||$.nodeName(c,"body")){break}a="backgroundColor"}while(c=c.parentNode);return getRGB(b)};
You can also animate colors using CSS3 transitions but it's only supported by modern browsers.
a.test {
color: red;
-moz-transition-property: color; /* FF4+ */
-moz-transition-duration: 1s;
-webkit-transition-property: color; /* Saf3.2+, Chrome */
-webkit-transition-duration: 1s;
-o-transition-property: color; /* Opera 10.5+ */
-o-transition-duration: 1s;
-ms-transition-property: color; /* IE10? */
-ms-transition-duration: 1s;
transition-property: color; /* Standard */
transition-duration: 1s;
}
a.test:hover {
color: blue;
}
Using shorthand property:
/* shorthand notation for transition properties */
/* transition: [transition-property] [transition-duration] [transition-timing-function] [transition-delay]; */
a.test {
color: red;
-moz-transition: color 1s;
-webkit-transition: color 1s;
-o-transition: color 1s;
-ms-transition: color 1s;
transition: color 1s;
}
a.test {
color: blue;
}
Unlike regular javascript transitions, CSS3 transitions are hardware accelerated and therefore smoother. You can use Modernizr, to find out if the browser supports CSS3 transitions, if it didn't then you can use jQuery as a fallback:
if ( !cssTransitions() ) {
$(document).ready(function(){
$(".test").hover(function () {
$(this).stop().animate({ backgroundColor: "red" },500)
}, function() {
$(this).stop().animate({ backgroundColor: "blue" },500)}
);
});
}
Remember to use stop() to stop the current animation before starting a new one otherwise when you pass over the element too fast, the effect keeps blinking for a while.
For anyone finding this. Your better off using the jQuery UI version because it works on all browsers. The color plugin has issues with Safari and Chrome. It only works sometimes.
You can use 2 divs:
You could put a clone on top of it and fade the original out while fading the clone in.
When the fades are done, restore the original with the new bg.
$(function(){
var $mytd = $('#mytd'), $elie = $mytd.clone(), os = $mytd.offset();
// Create clone w other bg and position it on original
$elie.toggleClass("class1, class2").appendTo("body")
.offset({top: os.top, left: os.left}).hide();
$mytd.mouseover(function() {
// Fade original
$mytd.fadeOut(3000, function() {
$mytd.toggleClass("class1, class2").show();
$elie.toggleClass("class1, class2").hide();
});
// Show clone at same time
$elie.fadeIn(3000);
});
});​
jsFiddle example
.toggleClass()
.offset()
.fadeIn()
.fadeOut()
I used a combination of CSS transitions with JQuery for the desired effect; obviously browsers which don't support CSS transitions will not animate but its a lightweight option which works well for most browsers and for my requirements is acceptable degradation.
Jquery to change the background color:
$('.mylinkholder a').hover(
function () {
$(this).css({ backgroundColor: '#f0f0f0' });
},
function () {
$(this).css({ backgroundColor: '#fff' });
}
);
CSS using transition to fade background-color change
.mylinkholder a
{
transition: background-color .5s ease-in-out;
-moz-transition: background-color .5s ease-in-out;
-webkit-transition: background-color .5s ease-in-out;
-o-transition: background-color .5s ease-in-out;
}
These days jQuery color plugin supports following named colors:
aqua:[0,255,255],
azure:[240,255,255],
beige:[245,245,220],
black:[0,0,0],
blue:[0,0,255],
brown:[165,42,42],
cyan:[0,255,255],
darkblue:[0,0,139],
darkcyan:[0,139,139],
darkgrey:[169,169,169],
darkgreen:[0,100,0],
darkkhaki:[189,183,107],
darkmagenta:[139,0,139],
darkolivegreen:[85,107,47],
darkorange:[255,140,0],
darkorchid:[153,50,204],
darkred:[139,0,0],
darksalmon:[233,150,122],
darkviolet:[148,0,211],
fuchsia:[255,0,255],
gold:[255,215,0],
green:[0,128,0],
indigo:[75,0,130],
khaki:[240,230,140],
lightblue:[173,216,230],
lightcyan:[224,255,255],
lightgreen:[144,238,144],
lightgrey:[211,211,211],
lightpink:[255,182,193],
lightyellow:[255,255,224],
lime:[0,255,0],
magenta:[255,0,255],
maroon:[128,0,0],
navy:[0,0,128],
olive:[128,128,0],
orange:[255,165,0],
pink:[255,192,203],
purple:[128,0,128],
violet:[128,0,128],
red:[255,0,0],
silver:[192,192,192],
white:[255,255,255],
yellow:[255,255,0]
Simply add the following snippet bellow your jquery script and enjoy:
<script src="https://cdn.jsdelivr.net/jquery.color-animation/1/mainfile"></script>
See the example
Reference for more info
I like using delay() to get this done, here's an example:
jQuery(element).animate({ backgroundColor: "#FCFCD8" },1).delay(1000).animate({ backgroundColor: "#EFEAEA" }, 1500);
This can be called by a function, with "element" being the element class/name/etc. The element will instantly appear with the #FCFCD8 background, hold for a second, then fade into #EFEAEA.
I stumbled across this page with the same issue, but the following problems:
I can't include an extra jQuery plugin file with my current set-up.
I'm not comfortable pasting large blocks of code that I don't have time to read over and validate.
I don't have access to the css.
I hardly had any time for implementation (it was only a visual improvement to an admin page)
With the above that pretty much ruled out every answer. Considering my fade of colour was very simple, I used the following quick hack instead:
element
.css('color','#FF0000')
;
$('<div />')
.css('width',0)
.animate(
{'width':100},
{
duration: 3000,
step:function(now){
var v = (255 - 255/100 * now).toString(16);
v = (v.length < 2 ? '0' : '') + v.substr(0,2);
element.css('color','#'+v+'0000');
}
}
)
;
The above creates a temporary div that is never placed in the document flow. I then use jQuery's built-in animation to animate a numeric property of that element - in this case width - which can represent a percentage (0 to 100). Then, using the step function, I transfer this numeric animation to the text colour with a simple hex cacluation.
The same could have been achieved with setInterval, but by using this method you can benefit from jQuery's animation methods - like .stop() - and you can use easing and duration.
Obivously it's only of use for simple colour fades, for more complicated colour conversions you'll need to use one of the above answers - or code your own colour fade math :)
Try this one:
(function($) {
var i = 0;
var someBackground = $(".someBackground");
var someColors = [ "yellow", "red", "blue", "pink" ];
someBackground.css('backgroundColor', someColors[0]);
window.setInterval(function() {
i = i == someColors.length ? 0 : i;
someBackground.animate({backgroundColor: someColors[i]}, 3000);
i++;
}, 30);
})(jQuery);
you can preview example here: http://jquerydemo.com/demo/jquery-animate-background-color.aspx
ColorBlend plug in does exactly what u want
http://plugins.jquery.com/project/colorBlend
Here is the my highlight code
$("#container").colorBlend([{
colorList:["white", "yellow"],
param:"background-color",
cycles: 1,
duration: 500
}]);
If you wan't to animate your background using only core jQuery functionality, try this:
jQuery(".usercontent").mouseover(function() {
jQuery(".usercontent").animate({backgroundColor:'red'}, 'fast', 'linear', function() {
jQuery(this).animate({
backgroundColor: 'white'
}, 'normal', 'linear', function() {
jQuery(this).css({'background':'none', backgroundColor : ''});
});
});
To change background color with animate effect without jQueryUI:
selector.css({
backgroundColor: "#555",
transition: "background-color 1.8s"
});
Try to use it
-moz-transition: background .2s linear;
-webkit-transition: background .2s linear;
-o-transition: background .2s linear;
transition: background .2s linear;
Try this one:
jQuery(".usercontent").hover(function() {
jQuery(this).animate({backgroundColor:"pink"}, "slow");
},function(){
jQuery(this).animate({backgroundColor:"white"}, "slow");
});
Revised way with effects:
jQuery(".usercontent").hover(function() {
jQuery(this).fadeout("slow",function(){
jQuery(this).animate({"color","yellow"}, "slow");
});
});

Transition between two colours on mouse move with Javascript

If the left half of the screen is a specific rgb value, and the right is another, how would one smoothly transition depending on mouse position between those two on mousemove?
So that when the mouse in at the far left, it's one colour, and far right it's the other. In the middle it would be the half way point.
Something like this: http://jsfiddle.net/j08691/BrZjJ/ - But based on set colours, not arbitrary ones.
var $el = $('div');
var p_x, p_y,
window_width = window.innerWidth,
window_height = window.innerHeight;
var m = {
moving_left: false,
moving_up: false,
last_x: 0,
last_y: 0,
x: 0,
y: 0
};
var colors = {
orange: { r: 238, g: 119, b: 0 },
blue: { r: 40, g: 203, b: 215 }
};
$el.on('mousemove', function(e){
m.x = e.pageX;
m.y = e.pageY;
m.moving_left = (m.x < m.last_x) ? true : false;
m.moving_up = (m.y < m.last_y) ? true : false;
m.last_x = m.x;
m.last_y = m.y;
});
function animateBackground() {
p_width = m.x / window_width;
p_height = m.y / window_height;
p_x = p_width.toFixed(2);
p_y = p_height.toFixed(2);
switch(true) {
// top left
case p_x <= 0.5 && p_y <= 0.5:
fr = colors.orange.r;
fg = colors.orange.g;
fb = colors.orange.b;
break;
// bottom right
default:
fr = colors.blue.r;
fg = colors.blue.g;
fb = colors.blue.b;
break;
}
$el.css({
backgroundColor: 'rgb('+fr+', '+fg+', '+fb+')'
});
requestAnimationFrame(animateBackground);
}
requestAnimationFrame(animateBackground);
https://jsfiddle.net/o32juay5/
I'm using something similar to the above, (except using 4 colours on four corners, but for simplicity...). I just can't work out in my head how to transition between two colours...
Any ideas?
Thanks.
You need to calculate the colors mathematically according to the mouse position.
For each of the R, G, B values: Take values for the two colors, determine the range between them, select a position inside that range according to the mouse position, and combine them into a background-color to be used in CSS.
https://jsfiddle.net/kbpyxxcn/6/
If you want to use this method with four colors, your calculations will become more complicated, unless you also define a color for the center.
Add the CSS property transition and it works:
https://jsfiddle.net/o32juay5/2/
div {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
-ms-transition: background-color 1s;
-webkit-transition: background-color 1s;
transition: background-color 1s;
}
If you make it with javascript the performance will be less than this css property.

Greensock fading in and out on background image change

I have never used GreenSock before. The background image changes fine, it switches and scales in and out however the issues I am facing are as follows:
The first background image on the sprite to show does not scale in and out but all the others do, how can I fix this?
It seems to change the background then scale in and out. So there is a small delay between the changing of the background image and the start of scale animation. Is there anyway to tighten this up so it scales as its changed to make it a more smoother transition?
JavaScript:
// Avatar animations
var avatarInterval;
var fadePulse = true; // true: will fade avatar images and pulse in and out once changed
// false: will slide the avatars in and out
var avatarCount = 11; // set the amount of avatars in the sprite image
var avatarSpeed = 1000; // set the avatar transition speed
var avatarHeight = 250; // set the height of a single avatar image
var avatarTotalHeight = 2750; // set the total height of the avatar sprite image
function startAvatarAnimation() {
var i = 0;
$(".avatars").show();
// Loop through avatar background images on sprite
avatarInterval = setInterval(function(){
i++;
if(i > avatarCount){
i = 0;
}
// Let's change the background
$(".avatars").css({'background-position' : '0 -' + (i*avatarHeight) + 'px' });
// avatar fading / pulse effect
if (fadePulse == true) {
// Now some scaling effects!
TweenMax.to(avatars, 0.1, {
css: {
// 'background-position': '0 -' + (i*avatarHeight) + 'px',
scaleX: 1.1,
scaleY: 1.1,
transformOrigin: "center center"
},
onComplete: scaleOut,
onCompleteParams: [avatars],
delay: 0.1,
ease: Power3.easeInOut
});
// Bring the scale back to normal
function scaleOut(el) {
TweenMax.to(el, 0.1, {
css: {
scaleX: 1.0,
scaleY: 1.0,
transformOrigin: "center center",
autoAlpha: 1,
},
ease: Power2.easeOut
});
}
} else {
// avatar sliding effect
}
}, avatarSpeed);
return false;
}
Take a look at this result.
Snippet:
var avatarCount = 6;
var avatarHeight = 250;
var avatarTotalHeight = 1500;
var avatars = $(".avatars");
var animDuration = 0.1;
var i = 0;
var timeline = new TimelineMax({ paused: true, repeat: -1 });
timeline.to(avatars, animDuration, {
scaleX: 1.1,
scaleY: 1.1,
ease: Power3.easeIn,
onComplete: onCompleteScaleIn
});
timeline.to(avatars, animDuration, {
scaleX: 1.0,
scaleY: 1.0,
ease: Power3.easeOut
});
function onCompleteScaleIn() {
i++;
i = i >= avatarCount ? 0 : i;
TweenMax.set(avatars, {
backgroundPosition: '0 -' + (i * avatarHeight) + 'px'
});
}
timeline.play();
#container {} #container,
.section {
overflow: hidden;
position: relative;
}
.section {
position: absolute;
}
#container .logo_o2 {
bottom: 10px;
right: 20px;
}
.section {
position: relative;
height: 250px;
width: 300px;
display: block;
}
.section .abs {
position: absolute;
}
.section h1,
.section h2,
.section h3,
.section h4 {
font-size: 21px;
width: 100%;
text-align: center;
letter-spacing: 0;
}
.section1,
.section2,
.section3,
.section4,
.section5,
.section6 {} .avatars {
background-image: url(http://s1.postimg.org/dwt9yu9b3/test_bg_sprite.png);
background-repeat: no-repeat;
background-size: cover;
display: block;
height: 250px;
width: 300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/latest/TweenMax.min.js"></script>
<div class="section section3">
<div class="abs clouds"></div>
<div id="avatars" class="abs avatars"></div>
</div>
Details:
First off, this result could have been achieved in a number of ways, more efficiently. Even within TweenMax there could have been a number of possible solutions. So, this attempt is in no way supposed to be the best.
Because you are already using GSAP; I have used TimelineMax, TweenMax's powerful cousin that makes sequencing of animations very easy.
So we have a timeline variable which carries an instance of TimelineMax object with default settings of: 1. initially paused and 2. indeterminate loops.
We then populate this timeline by using the method .to() which basically will start animation from wherever the object currently is. There are a plethora of methods and properties available for the GSAP platform, you should explore.
On the first line of .to() call, we have an onComplete callback pointing to a function.
This callback adjusts the backgroundPosition as per the current iteration.
Finally, there is another .to() call which does the same i.e. start the animation from whatever attributes avatars object currently possesses (in our case, scaleX & scaleY would be at 1.1 because of the first .to() call).
Note: by default, any new .to() (or .from() or .fromTo()) call is appended at the end of a timeline. Read more about the position parameter here.
Let me know if you have any questions.
Update: Here is another version using TweenMax only. Much leaner I guess.

Javascript/JQuery looping the body background color continuously

Im having alot of trouble trying to get JQuery and Javascript to loop through an array of colors in a for loop, set the background color of the body to each one, and then restart the process. I don't know if this is the best approach but I want the background color to switch extremely fast. This is what I have so far. Im trying to get it triggered by a JQuery event on a button.
$("#button6").click(function() {
$('#disclaimer').hide();
$('#button6').hide();
var colors = Array("red", "green", "blue", "purple" "yellow", "orange);
var count = 0;
while ( count < 1000 ) {
for(var i = 0; i < colors.length; i++) {
$('body').css("background-color", colors[i]);
$('body').delay(50);
}
count++;
}
});
.delay() works with animations, it doesn't delay just anything. I think setTimeout would work better for you here:
http://jsfiddle.net/thA9q/
var colors = ["red", "green", "blue", "purple", "yellow", "orange"];
var currentColor = 0;
function switchColor() {
if (currentColor >= colors.length) currentColor = 0;
$('body').css('background-color', colors[currentColor++]);
setTimeout(switchColor, 50);
}
switchColor();
look at the bellow snippet.
var c = ["#81d8d0", "#ffea64", "#89bc84", "#e5cb47", "#9d549c"];
var i = 0;
var myVar = setInterval(function () { myTimer() }, 1500);
function myTimer() {
document.getElementsByTagName('body')[0].style.background = c[i];
i = i + 1;
if (i >= c.length) i = 0;
}
http://jsfiddle.net/bhaumikmehta/8og7v8ad/6/
why don't you use svg + css?
Animate svg path fill using css
here is my code:
#keyframes fill {
0% {
fill: red;
}
20% {
fill: green;
}
40% {
fill: blue;
}
60% {
fill: purple;
}
80% {
fill: yellow;
}
100% {
fill: orange;
}
}
#fill {
fill: black;
animation-name: fill;
animation-duration: 50ms;
animation-iteration-count: infinite;
}
]]>
</style>
<rect id="fill" x="0" y="0" width="60" height="60"/>
you can copy it in to a file called something.svg and use it as an image with css.
#edit: somehow the code crashes on stackoverflow, but you can download my sample here: https://dl.dropboxusercontent.com/u/49774783/crazy.svg

Animating a glow in Raphael.js

I'm trying to achieve a pulsating glow effect in raphael.js. Here is my code http://jsfiddle.net/eaPSC/ I'm very sorry about the massive brain. ;)
I tried animating both the width of the glow effect and the opacity and neither seem to be influenced by animation at all. (The glow is static. I examined it by hiding the brain element, zooming in and checking out just the glow element, and there is simply no action.)
I tried animating a separate (non-glow) element using the same procedure and multiple attributes do get animated fine.
thanks!
You cannot animate the width or color properties of a glow. The glow is created by adding a stroke to a set of paths with zero fill. If you want to change the color or the width of the glow you have to animate the stroke or stroke-width properties.
http://jsfiddle.net/eaPSC/2/
Wrong: (quoted from your source):
anim = Raphael.animation({
width: 15,
opeacity: 1
}, 500);
Slightly More Correct:
anim = Raphael.animation({
"stroke-width": 15,
opacity: 1
}, 500);
But you will notice that this kills off the gradiented glow effect. If you actually look at the source code for glow() you can see that the final for loop creates a layered set of paths to create the gradient effect.
elproto.glow = function (glow) {
if (this.type == "text") {
return null;
}
glow = glow || {};
var s = {
width: (glow.width || 10) + (+this.attr("stroke-width") || 1),
fill: glow.fill || false,
opacity: glow.opacity || .5,
offsetx: glow.offsetx || 0,
offsety: glow.offsety || 0,
color: glow.color || "#000"
},
c = s.width / 2,
r = this.paper,
out = r.set(),
path = this.realPath || getPath[this.type](this);
path = this.matrix ? mapPath(path, this.matrix) : path;
for (var i = 1; i < c + 1; i++) {
out.push(r.path(path).attr({
stroke: s.color,
fill: s.fill ? s.color : "none",
"stroke-linejoin": "round",
"stroke-linecap": "round",
"stroke-width": +(s.width / c * i).toFixed(3),
opacity: +(s.opacity / c).toFixed(3)
}));
}
return out.insertBefore(this).translate(s.offsetx, s.offsety);
};
So if you just fix the stroke-width for all of these paths, it kills the glow effect as you will see in the example. There isn't really an easy answer to this. You could possibly animate it yourself using setInterval to remove the old glow and add a new one with a new width, but it doesn't sound like a very efficient method.
i've been able to correct this issue without the timing issue as shown in your jsfiddle demo by adding the following to resume.
elproto.resume = function (anim) {
for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) {
var e = animationElements[i];
if (eve("raphael.anim.resume." + this.id, this, e.anim) !== false) {
delete e.paused;
this.status(e.anim, e.status,**e.totalOrigin**);
}
}
return this;
};

Categories

Resources