JQuery background color animate not working - javascript

I want to change the background color of 'exampleDiv' from the original white background to when I call the code below to immediate change the background yellow and then fade back to the original white background.
$("#exampleDiv").animate({ backgroundColor: "yellow" }, "fast");
However, this code does not work.
I have only the JQuery core and JQuery UI linked to my web page.
Why doesn't the code above work?

I've had varying success with animate, but found that using its built in callback plus jQuery's css seems to work for most cases.
Try this function:
$(document).ready(function () {
$.fn.animateHighlight = function (highlightColor, duration) {
var highlightBg = highlightColor || "#FFFF9C";
var animateMs = duration || "fast"; // edit is here
var originalBg = this.css("background-color");
if (!originalBg || originalBg == highlightBg)
originalBg = "#FFFFFF"; // default to white
jQuery(this)
.css("backgroundColor", highlightBg)
.animate({ backgroundColor: originalBg }, animateMs, null, function () {
jQuery(this).css("backgroundColor", originalBg);
});
};
});
and call it like so:
$('#exampleDiv').animateHighlight();
Tested in IE9, FF4, and Chrome, using jQuery 1.5 (do NOT need UI plugin for this). I didn't use the jQuery color plugin either - you would only need that if you want to use named colors (e.g. 'yellow' instead of '#FFFF9C').

I believe you also need JQuery Color Animations.

I had the same problem and I was able to get everything to work when I included the correct js files.
<script src="/Scripts/jquery-1.9.1.js"></script>
<script src="/Scripts/jquery-ui-1.8.20.js"></script>
<script src="/Scripts/jquery.color-2.1.2.js"></script>
I took it a step further and found a nice extension someone wrote.
jQuery.fn.flash = function (color, duration) {
var current = this.css('backgroundColor');
this.animate({ backgroundColor: 'rgb(' + color + ')' }, duration / 2)
.animate({ backgroundColor: current }, duration / 2);
}
The above code allows me to do the following:
$('#someId').flash('255,148,148', 1100);
That code will get your element to flash to red then back to its original color.
Here's some sample code. http://jsbin.com/iqasaz/2

The jQuery UI has a highlight effect that does exactly what you want.
$("exampleDiv").effect("highlight", {}, 5000);
You do have some options like changing the highlight colour.

Animating the backgroundColor is not supported in jQuery 1.3.2 (or earlier). Only parameters that take numeric values are supported. See the documentation on the method. The color animations plugin adds the ability to do this as of jQuery 1.2.

I came across the same issue and ultimately it turned out to be multiple call of jquery's js file on the page.
While this works absolutely fine with any other methods and also with animate when tried with other css properties like left, but it doesn't work for background color property in animate method.
Hence, I removed the additional call of jquery's js file and it worked absolutely fine for me.

For me, it worked fine with effects.core.js. However, I don't recall whether that's really required. I think that it only works with hexadecimal values. Here's a sample hover code that makes things fade as you hover. Thought it might be useful:
jQuery.fn.fadeOnHover = function(fadeColor)
{
this.each(function()
{
jQuery(this).data("OrigBg",jQuery(this).css("background-color"));
jQuery(this).hover(
function()
{
//Fade to the new color
jQuery(this).stop().animate({backgroundColor:fadeColor}, 1000)
},
function()
{
//Fade back to original color
original = jQuery(this).data("OrigBg");
jQuery(this).stop().animate({backgroundColor:original},1000)
}
);
});
}
$(".nav a").fadeOnHover("#FFFF00");

I had to use the color.js file to get this to work. I'm using jquery 1.4.2.
Get the color.js here

Just added this snippet below jquery script and it immediately started working:
<script src="https://cdn.jsdelivr.net/jquery.color-animation/1/mainfile"></script>
Source

Related

Using complete option for jquery animate

I have a gif image in my html. I want to make the image "walk" so I'm using jquery .animate() the walking is fine, now, once it reaches the other side of the screen, I'd like to hide the image so I'm trying to use the complete option. My code looks like so:
$(document).ready(function() {
for(var i = 0; i < 500; i = i + 20) {
$("#animate-gif").animate({backgroundPositionX: i}, 50,
function() { alert("finished"); }); }
});
However, the alert does not show. I've also tried doing the following:
duration : 50, complete : function()
{backgroundPositionX: i}, {duration : 50, complete :function()
But neither worked and I'm getting a warning in my debugger "Unexpected token :". So my question is, how exactly do you add a complete option for the animate function in jquery? I've tried looking through the documentation and some examples and what i've tried are pretty much what I've seen.
I don't understand the purpose of the for loop. Try just calling animate() once:
http://jsfiddle.net/W5SjR/1/
$(document).ready(function() {
$("#animate-gif").animate({backgroundPositionX: "100%"}, 500, function() { alert("finished"); });
});
Your complete function looks fine. Is it possible that you checked "don't allow this page to show popups"?
I would also suggest using console.log() instead of alert().
the general syntax of .animate is
$("selector").animate({"param":"value","param","value"},time,callback_function);
The callback function will be called after the completion of the animation
there are also other options like "step", "complete" and much more
You can check this fiddle where i would used some of them

Animate.CSS Replay?

I have an animation using Animate.CSS that I would like to have replay if the user would like but what I have attempted does not work. Here is the code:
HTML:
<div class="img-center">
<img src="path.jpg" class="feature-image animated rotateInDownRight" />
</div>
<p class="textcenter"> </p>
<div class="img-center">
Replay
</div>
JS:
var $j = jQuery.noConflict();
$j("#replay").click(function() {
$j('.feature-image').removeClass('animated rotateInDownRight').addClass('animated rotateInDownRight');
});
I do know the script itself works as I can see it happen in Firebug however that animation doesn't animate again. How do I achieve this with Animate.CSS?
This is just a guess but it appears that jQuery isn't "finished" removing the class before it adds it back in. I know this makes NO sense, but it's how JavaScript works. It can call the next function in the chain before all the stuff from the first one is finished. I poked around the code on Animate.CSS's site and saw that they use a timeout in their animation function. You might try the same. Here's their code:
function testAnim(x) {
$('#animateTest').removeClass().addClass(x);
var wait = window.setTimeout( function(){
$('#animateTest').removeClass()},
1300
);
}
What this is doing is exactly like what you are doing except that it waits for the animation to finish, then removes the classes. That way when the other class is added back in, it is truely "new" to the tag. Here is a slightly modified function:
function testAnim(elementId, animClasses) {
$(elementId).addClass(animClasses);
var wait = window.setTimeout( function(){
$(elementId).removeClass(animClasses)},
1300
);
}
Notice two things: First this code would allow you to change what element gets the animation. Second, you remove the classes you added after 1300 milliseconds. Still not 100% there, but it might get you further down the road.
It should be noted that if there is already some animation classes on the object it might break this JS.
found the right answer at animate.css issue#3
var $at = $('#animateTest').removeClass();
//timeout is important !!
setTimeout(function(){
$at.addClass('flash')
}, 10);
Actually a simpler version can avoid using JQuery too.
el.classList.remove('animated','flash');
//timeout is important !!
setTimeout(function(){
el.classList.add('animated','flash');
}, 10);
I believe the issue here is that when I remove the class it was adding the class to quickly. Here is how I solved this issue:
(HTML is same as above question).
JS:
var $j = jQuery.noConflict();
window.setTimeout( function(){
$j('.feature-image').removeClass('animated rotateInDownRight')},
1300);
$j("#replay").click(function() {
$j('.feature-image').addClass('animated rotateInDownRight');
});
What I believe is happening is the jQuery code is removing and adding the class to quickly. Regardless of the reason this code works.
If you wish you can also give a try to this javaScript side development that support animate.css animations. Here is an example of usage.
//Select the elements to animate and enjoy!
var elt = document.querySelector("#notification") ;
iJS.animate(elt, "shake") ;
//it return an AnimationPlayer object
//animation iteration and duration can also be indicated.
var vivifyElt = iJS.animate(elt, "bounce", 3, 500) ;
vivifyElt.onfinish = function(e) {
//doSomething ...;
}
// less than 1500ms later...changed mind!
vivifyElt.cancel();
Take a look here
My answer is a trick to add/remove the css class with a tint delay:
$('#Box').removeClass('animated').hide().delay(1).queue(function() {
$(this).addClass('animated').show().dequeue();
});
Also you can test it without hide/show methods:
$('#Box').removeClass('animated').delay(1).queue(function() {
$(this).addClass('animated').dequeue();
});
I fill it works smooth in chrome but it works with more unexpected delay in FF, so you can test this js timeout:
$('#Box').removeClass('animated');
setTimeout(function(){
$('#Box').addClass('animated');
}, 1);
This solution relies on React useEffect, and it's rather clean, as it avoids manipulating the class names directly.
It doesn't really answers the OP question (which seems to be using jQuery), but it might still be useful to many people using React and Animate CSS library.
const [repeatAnimation, setRepeatAnimation] = useState<boolean>(true);
/**
* When the displayedFrom changes, replay the animations of the component.
* It toggles the CSS classes injected in the component to force replaying the animations.
* Uses a short timeout that isn't noticeable to the human eye, but is necessary for the toggle to work properly.
*/
useEffect(() => {
setRepeatAnimation(false);
setTimeout(() => setRepeatAnimation(true), 100);
}, [displayedFrom]);
return (
<div
className={classnames('block-picker-menu', {
'animate__animated': repeatAnimation,
'animate__pulse': repeatAnimation,
})}
...
)

jQuery animate() pulse() not working

In the following code, the animate() function in click() works.
However, animate() or pulse() (when uncommented) in mouseenter() does not work either.
The pulse() function is provided by Jarrod Overson...
http://jarrodoverson.com/static/demos/jquery.pulse.html
sectionTitle = $j(this).find(".sectionTitle");
sectionTitle.click(function(){
if($j(this).parent().height() == sections[$j(this).parent().attr("id")]["height"]){
origHeight = sections[$j(this).parent().attr("id")]["origHeight"];
$j(this).parent().animate({height:origHeight},"slow");
}else{
height = sections[$j(this).parent().attr("id")]["height"];
$j(this).parent().animate({height:height},"slow");
}
})
sectionTitle.mouseenter(function(){
var properties = { "color" : '#F00' };
// $j(this).pulse(properties, 500, 3);
$j(this).animate({"background-color":'#F00'},"slow");
})
A live example of my code is here.
http://fantasticvisions.net/test/me/
The classs sectionTitle is applied to a number of the H2 elements on the above page. Clicking them will cause the content to expand, using jQuery animate(). However, the mouseenter() fails.
What am I missing here? I have tried a number of other variations on this, and none work. The mouseenter() event does fire, and the code is executed (I have traced this) but the effect never seems to happen.
.animate() is not working because jQuery by itself does not support animation of colors.
If you include jQuery UI, or a color animation plugin, this should work.

Animation with jCarousel

I am using jCarousel for image slider. I am new to jQuery so from the jCarousel documentation I can't figure out how to apply different animation effects.
Say I have one image at a slice, and I want the view image disappear slowly, and simultaneously the next picture appear in the same place. How can I achieve this effect? Is it a custom animation, that requires to write a new JS function, or it can be done via setting of jCarousel?
Karine, I believe you should use the easing configuration property. http://sorgalla.com/projects/jcarousel/#Configuration
Here you can specify the jquery easing effect you want to use (http://api.jquery.com/animate/). If you need something else you can create a custom animation. Here you can see an example http://sorgalla.com/projects/jcarousel/examples/special_easing.html.
Alternatively, you can obtain the desired effect using this code:
<script type="text/javascript">
function carouselFadeOut(carousel) {
var clipId = carousel.clip.context.id;
$('#' + clipId).fadeOut();
}
function carouselFadeIn(carousel) {
var clipId = carousel.clip.context.id;
$('#' + clipId).fadeIn();
}
jQuery(document).ready(function() {
jQuery('#mycarousel').jcarousel({visible : 1, scroll : 1,
itemLoadCallback: {
onBeforeAnimation: carouselFadeOut,
onAfterAnimation: carouselFadeIn
}
});
});
Hope it helps, Fabrizio

Highlight changes?

HTML:
<html>
<body>
<textarea>Original Text</textarea>
<button>Replace</button>
</body>
</html>
jQuery:
$(function() {
$('button').click(function () {
$('body').html($('body').html().replace('Original','New'));
});
});
http://jsfiddle.net/r7MgY/
Can I highlight changes somehow with a fading yellow background maybe?
As Sarfraz says, use the jQuery color plugin. Usage is the same as animate method in jQuery. The plugin overrides the animation methods for these properties: 'backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'.
jQuery animate method usage and info can be found here: http://api.jquery.com/animate/
Also, if you want to replace something in the HTML it's better to get the wrapper tag of the tag that contains what you want invoke the replace method on instead of search through the entire body as a string. Normally you'd use:
$('#idOfMyWrapperTag').html().replace('this', 'that')
But since you are using a textarea you can get it's value with this:
$('textarea').val().replace('this', 'that');
..fredrik
Because its a textarea, you cant inject any html directly into the content. You would have to overlay an absolute positioned element containing a red squiggle or similar - which becomes a bit of a nightmare when working out the exact location of the text.
If possible, ditch the textarea and just use an editable div or similar.
Can I highlight changes somehow with a
fading yellow background maybe?
You will have to use the jquery color plugin to fade the background color.
You might be able to workaround it with
$(function() {
$('button').click(function () {
$('body').html($('body').html().replace(/Original/g,'<span class="fade" style="opacity: 0; background-color: yellow;">New</span>'));
$('.fade').animate({
'opacity': 1
}, 1000, function(){
$(this).contents().unwrap();
});
});
});
If you don't want to include yet another plugin, you can simply use a little jQuery code to accomplish a fading overlay:
jQuery.fn.highlight = function() {
$(this).each(function() {
var el = $(this);
el.before("<div/>")
el.prev()
.width(el.width())
.height(el.height())
.css({
"position": "absolute",
"background-color": "#ffff99",
"opacity": ".9"
})
.fadeOut(500);
});
}
$("#target").highlight();
Credit goes to this answer: https://stackoverflow.com/a/11589350/1145177

Categories

Resources