jQuery animate() pulse() not working - javascript

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.

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

Mouseleave does not work with .each and delay?

I have written some code to change the colour of each letter inside an a tag and show a pop up when you hover the link.
The mouseenter function works fine but when you hover off the link I would like to do the reverse of the original change ( so change back to the origional colour ).
I take the delay out of the leave function it works but the effect is not as nice. I am confused as to why this works on the enter but not on the leave?
Another thing to mention is when it does change colour back to the grey the mouseenter function does not work again, which is kind of annoying.
Here is a link to the site so you can see what I am talking about and the link is the one at the bottom that says "Touch Marketing"
http://dev.touch-akl.com/colin/
Any help please?
My jQuery looks like this
$('#copyright a').mouseenter(function(){
var $letters = $(this).find('span'),
$sayhi = $(this).find('img'),
delay = 0;
$sayhi.animate({top:-30, 'opacity':1}, 500, "easeInOutExpo");
$letters.each(function(){
$(this).delay(delay).queue(function(){
$(this).css({'color':'#333'});
});
delay+=35;
}); // end each
}).mouseleave(function(){
var $letters = $(this).find('span'),
delay = 0;
$letters.each(function(){
$(this).delay(delay).queue(function(){
$(this).css({'color':'#333'});
});
delay+=35;
});
}); // end leave
jQuery .queue() is complicated to use correctly so unless you need to interact with other things in the jQuery animation queue, it is often much, much simpler to just use setTimeout() like this. You also should make delay a local variable so it isn't an implicit global variable.
}).mouseleave(function(){
var delay = 0;
$(this).find('span').each(function(){
var item = $(this);
setTimeout(function(){
item.css({'color':'#333'});
}, delay);
delay+=35;
});
}); // end leave
Most likely the problem is with the closure created by your functions in mouseenter and mouseleave. They're both referencing the same delay variable. You might want to separate them:
delayEnter = 0;
delayLeave = 0;

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 selector :not(:animated)

We're trying to make sure our JavaScript menu, which loads content, doesn't get overrun with commands before the content in question loads and is unfurled via .show('blind', 500), because then the animations run many times over, and it doesn't look so great. So I've got about six selectors that look like this:
("#center_content:not(:animated)")
And it doesn't seem to be having any effect. Trying only :animated has the expected effect (it never works, because it doesn't start animated), and trying :not(div) also has this effect (because #center_content is a div). For some reason, :not(:animated) seems not to be changing the results, because even when I trigger the selector while the div in question is visibly animated, the code runs. I know I've had success with this sort of thing before, but the difference here eludes me.
$("#center_content:not(:animated)").hide("blind", 500, function () {
var selector_str = 'button[value="' + url + '"]';
//alert(selector_str);
var button = $(selector_str);
//inspectProperties(button);
$("#center_content:not(:animated)").load(url, CenterContentCallback);
if (button) {
$("#navigation .active").removeClass("active");
button.addClass("active");
LoadSubNav(button);
}
});
I hope this provides sufficient context. I feel like the second selector is overkill (since it would only be run if the first selector succeeded), but I don't see how that would cause it to behave in this way.
Here's the snippet that seemed to be working in the other context:
function clearMenus(callback) {
$('[id$="_wrapper"]:visible:not(:animated)').hide("blind", 500, function() {
$('[id^="edit_"]:visible:not(:animated)').hide("slide", 200, function() {
callback();
});
});
}
Here, the animations queue instead of interrupt each other, but it occurs to me that the selector still doesn't seem to be working - the animations and associated loading events shouldn't be running at all, because the selectors should fail. While the queueing is nice behavior for animations to display, it made me realize that I seem to have never gotten this selector to work. Am I missing something?
Sometimes it's helpful to use .stop() and stop the current animation before you start the new animation.
$("#center_content").stop().hide("blind", 500, function () {});
Really depends on how it behaves within your environment. Remember that .stop() will stop the animation as it was (eg. halfway through hiding or fading)
I don't know if I understand it correctly, but if you want to make sure the user doesn't trigger the menu animation again while it's currently animating(causing it to queue animations and look retarded, this works and should help. I use an if-statement. And before any mouseover/off animation I add .stop(false, true).
$('whatever').click(function(){
//if center_content is not currently animated, do this:
if ($("#center_content").not(":animated")) {
$(this).hide(etc. etc. etc.)
}
//else if center_content IS currently animated, do nothing.
else {
return false;}
});
another example i found elsewhere:
if($("#someElement").is(":animated")) {
...
}
if($("#someElement:animated").length) {
...
}
// etc
then you can do:
$("#showBtn").attr("disabled", $("#someElement").is(":animated"));

JQuery background color animate not working

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

Categories

Resources