Animate.css shake effect not working every time - javascript

I'm making a Twitch Streamer application, that pulls some data using Twitch API, for a predetermined set of streamers.
I have three buttons to select all/online/offline channels, and I am looking to add the animated shake effect to all these buttons.
On my first attempt, I had a simple if/else check in place to make the shake work correctly - detect if the animated shake class already exists, if so, remove it, and then add it again. Else, just add it.
That didn't work. I found an answer here on SO that said it won't work that way because the addClass and removeClass occur so fast that the DOM doesn't have time to catch up.
I then used a queue with an anonymous function to add the class back after inducing a slight delay after the removeClass -
if ($(this).hasClass("animated shake")) {
$(this).removeClass("animated shake").delay(50).queue(
function() {
$(this).addClass("animated shake");
});
//$(this).addClass("animated shake");
} else {
$(this).addClass("animated shake");
}
Now, the shake effect works like 90% of the time, but if you keep switching back and forth between online/offline channels, there will be cases in between where the shake doesn't work.
Here's the app on Codepen.
I'd appreciate any help as to why it doesn't work every single time.
Note - The shake effect is on the online/offline buttons only, for now.

This works everytime :-D
function shakeButton($button) {
console.log('Shaking button')
$button.removeClass("animated shake");
setTimeout(
function() {
$button.addClass("animated shake");
},
25
);
}
$('button').click(function() {
shakeButton($(this));
});
<!-- Never mind, Just some Dummy html... -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.1/animate.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4>Never mind this, Just some Dummy Results</h4>
<h3>Check out the JS instead</h3>
<button>Button 1</button>
<button>Button 2</button>
<button>Button 3</button>
I just used setTimeout instead .delay() And it worked a treat :-)
Good Job, Your code is nice and well documented :-D A Few things though...
In your code... you repeat the same code at three places, Instead you can create a function with that code and call that function everywhere instead ;-) This will make debugging easier.
The if statement you use is not necessary... Just remove animate and shake classes every time ( it won't throw any error ;-) ) and add them after some time again, this will make code simpler.
This code is implemented in this snippet...
http://codepen.io/shramee/pen/EyZJjN

can you try something like this?
$('.btn').on('click', function()
{
// Siblings will target other buttons but not the current one
$(this).addClass('animated shake').siblings().removeClass('animated shake');
});
[EDIT] more relevent to your structure:
According to your example structure you can add a class to your buttons wrapper like .btnWrapper for convenience and do:
$('.btn').on('click', function()
{
var clicked = $(this);
clicked.addClass('animated shake').parents('.btnWrapper').siblings().find('.shake').removeClass('animated shake');
})

Related

jQuery function doesn't respond to ".click" until I move the cursor?

I have a website with a simple CSS style switcher. I use the following code for the function that handles clicking the two theme buttons, initiating the switch from dark to light and vice versa:
<script>
$(function() {
$(".light").click(function(){
$("link").attr("href", "css/lightHome.css");
$(".light").attr("disabled", "disabled");
$(".dark").removeAttr("disabled", "disabled")
})
$(".dark").click(function(){
$("link").attr("href", "css/home.css");
$(".dark").attr("disabled", "disabled");
$(".light").removeAttr("disabled", "disabled")
})
});
</script>
Everything about it operates exactly as I want, except the fact that when I click the button, nothing happens. But the second I shift the cursor position after the click, then the switch occurs. I don't have the best jQuery grasp, so I am hoping it is a simple lack of understanding regarding the DOM processes. Possibly having to do with the lack of "on ready"?
I've tried clicking and waiting several minutes, and nothing happens until I move the cursor.
The website:
http://watsoncn.info
Instead of completely switching the CSS file, an alternative solution would be to have a single CSS file with both your styles and then prefixing all your selectors with .theme.dark or .theme.light;
This would be pretty easy to do with nesting in LESS or SASS if you're using them (if you're not, you really should consider it. I can't imagine writing CSS without a preprocessor now), but might be cumbersome in pure CSS.
CSS:
.theme.dark <rest of selectors> {
//CSS
}
.theme.light <rest of selectors> {
//CSS
}
HTML:
<body class="theme">
and then code that runs on button clicks would be
$('body').addClass('dark')
$('body').removeClass('light')
and
$('body').addClass('light')
$('body').removeClass('dark')
Try this function:
function toggleCss(file, index) {
var oldFile = document.getElementsByTagName("link").item(index);
var newFile = document.createElement("link");
newFile.setAttribute("rel", "stylesheet");
newFile.setAttribute("type", "text/css");
newFile.setAttribute("href", file);
document.getElementsByTagName("head").item(0).replaceChild(newFile, oldFile);
}
$(".dark").on("click", function() {
toggleCss("css/lightHome.css");
$(".dark").attr("disabled", "disabled");
$(".light").removeAttr("disabled", "disabled");
});
$(".light").on("click", function() {
toggleCss("css/home.css");
$(".light").attr("disabled", "disabled");
$(".dark").removeAttr("disabled", "disabled");
});
Try to add use not a JavaScript, but the "checkbox trick". The checkbox handler set to display none, then style the main style, and on :checked style the handler like it clicked.
With this you can not use JavaScript but make it 100% working without any bugs, if you did everything right!
You can find the DevTips channel on YouTube
https://www.youtube.com/user/DevTipsForDesigners
on his channel you can find the tutorial how to do that!

One script causes another to stop working

I have a problem with a vertical scroll page where I'm using (intending to, that is) two nested quickscroll functions.
This is how it's supposed to look: - just remove the scrollbar in your mind. I'm just using
overflow:scroll
here to manually check on things.
Since JS isn't my forte (I have only very basic knowledge of it), I just got a piece of code that worked similarly, reverse engineered it by removing as much as I could from the HTML and CSS until I was left with the bare function, and plugged it into my own page in terms of the needed HTML and CSS as well as the code. I'm not using anything proprietary and I'm including author links, hoping that I'm on the safe side there (?)
So, the main scroll is a vertical one and inside one of the vertical sections I'm using this 'reverse engineered' horizontal quickscroll code.
The new (nested) script cancels out the main one. Any ideas how to fix this?
The main (vertical scroll) is the following:
<script>
$(document).ready(function() {
$('a.panel').click(function () {
$('a.panel').removeClass('selected');
$(this).addClass('selected');
/* I added this to hide the menu during scroll and I'm mighty proud of myself! :) */
$('.menu').addClass('hide');
$('.book_arrow').addClass('hide');
current = $(this);
$('body').scrollTo($(this).attr('href'), 2600, function(){
$('.menu').removeClass('hide');
$('.book_arrow').removeClass('hide');
});
return false;
});
});
</script>
It comes with these two linked files:
<script type="text/javascript" src="js/jquery-1.3.1.min.js"></script>
<script type="text/javascript" src="js/jquery.scrollTo.js"></script>
The conflicting code is a bit longer:
<script>
// initialize scrollable and return the programming API
var api = $("#scroll").scrollable({
items: '#tools'
// use the navigator plugin
}).navigator().data("scrollable");
// this callback does the special handling of our "intro page"
api.onBeforeSeek(function(e, i) {
// when on the first item: hide the intro
if (i) {
$("#intro").fadeOut("slow");
// dirty hack for IE7-. cannot explain
if ($.browser.msie && $.browser.version < 8) {
$("#intro").hide();
}
// otherwise show the intro
} else {
$("#intro").fadeIn(1000);
}
// toggle activity for the intro thumbnail
$("#t0").toggleClass("active", i == 0);
});
// a dedicated click event for the intro thumbnail
$("#t0").click(function() {
// seek to the beginning (the hidden first item)
$("#scroll").scrollable().begin();
});
</script>
...and it links to this file:
<script src="http://cdn.jquerytools.org/1.2.7/full/jquery.tools.min.js"></script>
Does it matter where in the HTML I place all these chunks? In isolation, both scripts are working.
I've read about a seemingly similar case here and I'm thinking that maybe in my case I'm also dealing with variables that are 'occupied' by one of the functions, but I'm not exactly sure what to change and where.
I'm absolutely positively looking forward to learning a major lesson from this problem! :)
Hoping that it doesn't cause the Stack to Overflow, I'll add some more (my solution) to my journey. Maybe it helps posterity to follow my learning curve...
I was able to get the nested quick scroll (as I call it) to work properly. Still a rookie in JS, I played around with that bit of script I had gotten and modified - the one that worked vertically - and stuffed the other, similar, script for the (inner) horizontal scroll into that first script! YAY! It worked. Here's how the final script looks:
<script>
$(document).ready(function() {
$('a.panel').click(function () {
$('.book_arrow').fadeOut();
## which prevents the vertical page flying past a lot of nav during scroll down ##
$('.fluid_centerbox').addClass('hide');
$('.fluid_centerbox').fadeOut();
## which makes the scroll smooth cause what's {display:none;} isn't going to be recalculated
and also lets the viewer appreciate the background images during scroll. the 'hide' is
instant and the .fadeOut is animated. Don't ask me why it worked best in this order! ##
current = $(this);
$('body').scrollTo($(this).attr('href'), 2600, function(){
$('.book_arrow').fadeIn();
$('.fluid_centerbox').fadeIn(), 40000;
});
return false;
});
$('a.panell').click(function () {
current = $(this);
$('.long_wrap').scrollTo($(this).attr('href'), 2600, function(){
});
return false;
});
## the panell is not a typo but a way to distinguish both scroll button types ##
});
</script>
And while I'm posting this, I see that in the inner quick scroll, there's an empty
function(){});
Maybe later I'll try to get rid of it, if possible.

Trigger event on animation complete (no control over animation)

I've a scenario that requires me to detect animation stop of a periodically animated element and trigger a function. I've no control over the element's animation. The animation can be dynamic so I can't use clever setTimeout.
Long Story
The simplified form of the problem is that I'm using a third party jQuery sliding banners plugin that uses some obfuscated JavaScript to slide banners in and out. I'm in need of figuring out a hook on slideComplete sort of event, but all I have is an element id. Take this jsfiddle as an example and imagine that the javascript has been obfuscated. I need to trigger a function when the red box reaches the extremes and stops.
I'm aware of the :animated pseudo selector but I think it will need me to constantly poll the required element. I've gone through this, this, and this, but no avail. I've checked jquery promise but I couldn't figure out to use that in this scenario. This SO question is closest to my requirements but it has no answers.
P.S. Some more information that might be helpful:
The element isn't created by JavaScript, it is present on page load.
I've control over when to apply the plugin (that makes it periodically sliding banner) on the element
Most of the slideshow plugins I have used use changing classes at the end of the animation... You could extend the "addClass" method of jQuery to allow you to capture the class change as long as the plugin you use is using that method like it should:
(function($){
$.each(["addClass","removeClass"],function(i,methodname){
var oldmethod = $.fn[methodname];
$.fn[methodname] = function(){
oldmethod.apply( this, arguments );
this.trigger(methodname+"change");
return this;
}
});
})(jQuery);
I threw together a fiddle here
Even with obfuscated code you should be able to use this method to check how they are sending in the arguments to animate (I use the "options" object when I send arguments to animate usually) and wrap their callback function in an anonymous function that triggers an event...
like this fiddle
Here is the relevant block of script:
(function($){
$.each(["animate"],function(i,methodname){
var oldmethod = $.fn[methodname];
$.fn[methodname] = function(){
var args=arguments;
that=this;
var oldcall=args[2];
args[2]=function(){
oldcall();
console.log("slideFinish");
}
oldmethod.apply( this, args );
return this;
}
});
})(jQuery);
Well since you didn't give any indication as to what kind of animation is being done, I'm going to assume that its a horizontal/vertical translation, although I think this could be applied to other effects as well. Because I don't know how the animation is being accomplished, a setInterval evaluation would be the only way I can guess at how to do this.
var prevPos = 0;
var isAnimating = setInterval(function(){
if($(YOUROBJECT).css('top') == prevPos){
//logic here
}
else{
prevPos = $(YOUROBJECT).css('top');
}
},500);
That will evaluate the vertical position of the object every .5 seconds, and if the current vertical position is equal to the one taken .5 seconds ago, it will assume that animation has stopped and you can execute some code.
edit --
just noticed your jsfiddle had a horizontal translation, so the code for your jsfiddle is here http://jsfiddle.net/wZbNA/3/

Converting existing jQuery from click function to auto display with delay

Currently, homepage text is only displayed via a click function which initiates a slide out.
What I would like to do, is to change this so that it doesn't require a click to display. I'm wanting the text to display (fade in) after about 3 seconds of the page loading.
This is what I have at present:-
$('.introbox span').replaceWith(function(){
return '\
<div class="slideOutTip '+$(this).attr('class')+'" style="'+$(this).attr('style')+'">\
\
<div class="tipVisible">\
<div class="tipIcon"><div class="plusIcon"></div></div>\
<span class="tipTitle">'+$(this).attr('title')+'</span>\
</div>\
\
<div class="slideOutContent">\
<p>'+$(this).html()+'</p>\
</div>\
</div>';
});
It is when the 'plusIcon' is clicked, that the text slides out and is visible.
The listen out for the click function is...
$('.tipVisible').bind('click',function(){
var tip = $(this).parent();
So I'm presuming this is where I need to convert the necessary to use autoload with perhaps a setDelay and FadeIn although I'm not 100%.
Please could someone advise how this can be altered to not use a click but auto display after delay? Thanks in advance.
Attempted to add code in jsfiddle if it is easier to see what I'm trying to do - thanks.
Pretty simple: make a function with what you do at .tipVisible.click and then set a window.setTimeout(yourFunction, 3000);
#Comment: Your JS is already pretty complex, I probably would reorganize and recode everything so I can just give you a hint how it could be implemented (didn't work right away when I added it in your fiddle, but I'm a bit too lazy to find the problem there).
var animate = function(obj) {
var tip = obj ? $(obj).parent() : $(".tipVisible").parent();
/* If a open/close animation is in progress, exit the function */
if (tip.is(':animated')) return false;
if (tip.find('.slideOutContent').css('display') == 'none') {
tip.trigger('slideOut');
}
else tip.trigger('slideIn');
}
window.setTimeout( animate, 3000);
$('.tipVisible').bind('click', function() {
animate(this);
});
EDIT: Well this is doing something at least, now you have to figure out what needs to be done when and how ;)
PS: You used jQuery but loaded Mootools framework... Mootools doesn't know $(document).ready()

How can I reveal content and maintain its visibility when mousing to a child element?

I'm asking a question very similar to this one—dare I say identical?
An example is currently in the bottom navigation on this page.
I'm looking to display the name and link of the next and previous page when a user hovers over their respective icons. I'm pretty sure my solution will entail binding or timers, neither of which I'm seeming to understand very well at the moment.
Currently, I have:
$(document).ready(function() {
var dropdown = $('span.hide_me');
var navigator = $('a.paginate_link');
dropdown.hide();
$(navigator).hover(function(){
$(this).siblings(dropdown).fadeIn();
}, function(){
setTimeout(function(){
dropdown.fadeOut();
}, 3000);
});
});
with its respective HTML (some ExpressionEngine code included—apologies):
<p class="older_entry">Older<span class="hide_me">Older entry:
<br />
{title}</span></p>
{/exp:weblog:next_entry}
<p class="blog_home">Blog Main<span class="hide_me">Back to the blog</span></p>
{exp:weblog:prev_entry weblog="blog"}
<p class="newer_entry">Newer<span class="hide_me">Newer entry:
<br />
{title}</span></p>
This is behaving pretty strangely at the moment. Sometimes it waits three seconds, sometimes it waits one second, sometimes it doesn't fade out altogether.
Essentially, I'm looking to fade in 'span.hide_me' on hover of the icons ('a.paginate_link'), and I'd like it to remain visible when users mouse over the span.
Think anyone could help walk me through this process and understand exactly how the timers and clearing of the timers is working?
Thanks so much, Stack Overflow. You guys have been incredible as I walk down this road of learning to make the internet.
If you just want to get it working, you can try to use a tooltip plugin like this one.
If you want to understand how this should be done: first, get rid of the timeout, and make it work without it. The difference (from the user's point of view) is very small, and it simplifies stuff (developing and debugging). After you get it working like you want, put the timeout back in.
Now, the problem is you don't really want to hide the shown element on the navigator mouse-out event. You want to hide it in its own mouse out event. So I think you can just pass the first argument to the navigator hover function, and add another hover to dropdowns, that will have an empty function as a first argument, and the hiding code in its second argument.
EDIT (according to your response to stefpet's answer)
I understand that you DO want the dropdown to disappear if the mouse moves out of the navigator, UNLESS its moved to the dropdown itself. This complicates a little, but here is how it can be done: on both types of items mouse-out event, you set a timer that calls a function that hides the dropdown. lets say the timer is 1 second. on both kind of item mouse-in even, you clear this timer (see the w3school page on timing for syntax, etc). plus, in the navigator's mouse-in you have to show the dropdown.
Another issue with the timer in your code is that it will always execute when mouse-out. Due to the 3 seconds delay you might very well trigger it again when mouse-over but since the timer still exist it will fade out despite you actually have the mouse over the element.
Moving the mouse back and forth quickly will trigger multiple timers.
Try to get it to work without the timer first, then (if really needed) add the additional complexity with the delay (which you must keep track of and remove/reset depending on state).
Here was the final working code, for anyone who comes across this again. Feel free to let me know if I could have improved it in any ways:
$(document).ready(function() {
var dropdown = $('span.hide_me');
var navigator = $('a.paginate_link');
dropdown.hide();
$(navigator).hover(function(){
clearTimeout(emptyTimer);
$(this).siblings(dropdown).fadeIn();
}, function(){
emptyTimer = setTimeout(function(){
dropdown.fadeOut();
}, 500);
});
$(dropdown).hover(function(){
clearTimeout(emptyTimer);
}, function(){
emptyTimer = setTimeout(function(){
dropdown.fadeOut();
}, 500);
});
});

Categories