Reputation: 722
I wanna pass an object from jquery using a selector to a javascript function like below.
flash($("#something span"), "#fff", 250);
but it does not seem to be working.
and I am not sure what to put in the javascript function. What I make now is:
function flash(obj,color1,color2,duration) {
obj.animate({backgroundColor:color1},duration);
setTimeout(function(){this.animate({backgroundColor:color2},duration);},duration);
}
or is there another way instead of passing an object? for example, in jquery: $("this").flash("#f79999", "#eee", 250);
but then how to define the javascript function?
Upvotes: 0
Views: 179
Reputation: 18078
With the jQuery.Color plugin installed in the page (ack. @Jonathan Lonowski) ...
You can avoid passing an object by using javascript's .call()
or .apply()
.
Here's an example :
$(function() {
function flash(color, duration) {
this.animate({backgroundColor:color}, duration);
}
$("#something span").on('click', function() {
flash.call($(this), "#fff", 250);
});
$("#something_else span").on('click', function() {
flash.apply($(this), ["#fff", 250]);
});
});
.call()
and .apply()
aren't really necessary here; regular function calls would suffice.
.call()
and .apply()
are normally used in cases where you need to call a method of one object but give it the context of another object. By doing so, the method is made to operate on a different this
.
Upvotes: 0
Reputation: 123563
You'll have to include the jQuery.Color plugin to animate properties like background-color
.
From "Animation Properties and Values:"
All animated properties should be animated to a single numeric value, except as noted below; most properties that are non-numeric cannot be animated using basic jQuery functionality (For example,
width
,height
, orleft
can be animated butbackground-color
cannot be, unless the jQuery.Color() plugin is used). [...]
is there another way instead of passing an object? for example, in jquery: $("this").flash("#fff",250);
jQuery's Plugins/Authoring should help with this. But, you could define it as:
jQuery.fn.flash = function (color, duration) {
return this.animate({ backgroundColor: color }, duration);
};
$('#something span').flash('#fff', 250);
Upvotes: 0
Reputation: 2373
You have a simple syntax error.
ojb.animate({backgroundColor:color},duration);
Should be
obj.animate({backgroundColor:color},duration);
Upvotes: 1