Do you know any dropdown menu scripts out there written in plain javascript, but not relying on jQuery?
I know how to achieve this with CSS, but I'd also like to add a nice fade effect and make it wait 1 second after the mouse is outside the menu, then close it if the mouse doesn't come back within the menu area.
I think I could implement the fade effect using the CSS "transition" property, but I have no clue on how to add the delay on mouseOut
I like this one, it's only 1.2 KB, the code is simple to modify:
http://www.scriptiny.com/2008/11/drop-down-menu/
You can change the time by modifying the "t" variable.
You could use the transition-delay-property and do the following:
remove the "delay-class", when the user enters the menu
add the "delay-class" when the user leaves the menu
See: https://developer.mozilla.org/en/CSS/transition-delay
Or you could do it like this (note: just pseudo code):
var timer = null;
function onenter() {
showSubMenu();
clearTimeout(timer);
timer = null;
}
function onleave() {
overMenu = false;
timer = setTimeout( function () { hideSubMenu(); } , 1000 );
}
Related
So I've got a little website, that shows div when I click a link, so the window is on the front.
Just click on the big green frame, and you'll see the window opening. Now the thing is that, if you open it, and try to scroll, without having clicked the content, it won't scroll, while it should. How can I fix this ?
The code called is this one, the animation thing is based on keyframes.
function displayBox(boxId, closeButtonId) {
displayButton(closeButtonId);
var Box = document.getElementById(boxId);
Box.setAttribute('class', 'boxIn');
Box.setAttribute('tabIndex', '0');
}
function displayButton(buttonId) {
var Box = document.getElementById(buttonId);
Box.setAttribute('class', 'buttonIn');
}
function hideBox(boxId, closeButtonId) {
var Box = document.getElementById(boxId);
Box.setAttribute('class', 'boxOut');
setTimeout(function(){var Box = document.getElementById(boxId);
Box.setAttribute('class', 'invisible');},500);
hideButton(closeButtonId);
}
function hideButton(buttonId) {
var Box = document.getElementById(buttonId);
Box.setAttribute('class', 'invisible');
}
Thank you in advance
You need to set focus on the new popup. Try to add Box.focus() call to displayBox function:
function displayBox(boxId, closeButtonId) {
displayButton(closeButtonId);
var Box = document.getElementById(boxId);
Box.setAttribute('class', 'boxIn');
Box.setAttribute('tabIndex', '0');
setTimeout(function() {
Box.focus();
}, 300);
}
Note, that since you animate your modal popup you need to focus content after animation is complete. The simplest way to achieve it is to invoke focus() after timeout equal to animation duration, in your case 300ms. If you don't want to hardcode animation timing in the JS function, then you should listen animationend event.
You have set overflow: hidden for your html tag in css and so the page won't scroll.
Remove it to fix.
Overflow is a proprerty that explains how to handle what doesn't fit window size. Hidden means: hide it and doesn't show at all. Scroll is the default if you don't specify anything.
I have a menu composed of three options.
Clicking on one causes a container div to "FadeInDown".
Then, its contents "FadeIn".
Clicking on another menu item or anywhere else on the page causes the
contents to "FadeOut" then container div to "FadeOutUp".
Here is the fiddle that I have been testing jsfiddle
$(document).ready(function() {
$('.container').each(function() {
animationHover(this,'.fadeInDown');
});
});
I'm not very familiar with jQuery and have been trying to use animate-css to get me along. Thanks for any help and tips in advance and welcome coding criticism :)
My answer is mainly based on JQuery and its animate function (http://api.jquery.com/animate/) . Here is the fiddle :
http://jsfiddle.net/awmat/7/
I use JavaScript objects like fadeInDown to animate the container.
var fadeInDown = {
opacity:1,
top: "50px"
};
And i use the complete callback function of animate to make the content appear after the container.
To manage several div (one for each menu item), I use id as selectors, but since the "click and display" function remains the same, I used a "builder" : (this uses a closure, so if you're not familiar with JavaScript, you may have to read several times to understand what is going on)
var menuClickCallbackBuilder = function(menuItem){
var container = $('#container' + menuItem);
var content = container.find('.content');
var showContent = function(){
content.animate({opacity:1},{duration:1000});
};
return function() {
var activeContainer = $('.active');
var hideContainer = function(){
activeContainer.animate(fadeOutUp,1000);
};
activeContainer.find('.content').animate({opacity:0},{duration: 1000, complete : hideContainer});
activeContainer.removeClass("active");
if(activeContainer[0] != container[0])
{
var timeout = activeContainer[0] ? 2000 : 0 ;
setTimeout(function(){
container.animate(fadeInDown,{duration : 1000, complete :showContent});
},timeout);
container.addClass("active");
}
}
};
This way, when you add the add the click callbacks, you can just do :
$(document).ready(function(){
// note that menuClickCallbackBuilder(1) returns a function
// again if you're not familiar with JS, you may have to re-read menuClickCallbackBuilder
$('#menuLink1').on('click', menuClickCallbackBuilder(1));
$('#menuLink2').on('click', menuClickCallbackBuilder(2));
$('#menuLink3').on('click', menuClickCallbackBuilder(3));
});
Some improvements you can bring to this :
Factor the durations into a variable (e.g animationDurationInSeconds) so that if you want to change the speed of the animation, you only have 1 thing to change. (#Huangism: and right after you did that, make animation faster so that it gets more dynamic)
(From #Huangism) : stop it from going crazy when people cicks on the menu 10 times really fast
Actually, I think you don't need 3 different containers, you could do it with just one container (though I don't know if it would be considered an improvement)
There is probably a way to use CSS classes instead of fadeInDown and fadeOutUp JS objects. That would be cleaner, I think you should keep styles in CSS as much as you can.
There is no need for different IDs for menu items, you could do the exact same thing with a loop.
Whatever your imagination wants to add
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/
I am working on some tabbed navigation for my website and I have an issue I'd like to fix.
I've been scrambling my head all day and getting nowhere. Would really appreciate some help.
Here be the code: http://jsfiddle.net/EghAt/
1) Notice when you click Tab 1 and then immediately click Tab 2, Tab 1 continues to loop out all the results.
I would prefer if this stopped looping Tab 1 results and just started looping Tab 2 results.
Is this possible?
How do I achieve this?
Many thanks for any pointers
You can stop the previous animation in this function of yours, by adding the .stop(true, true) you see in this revised function:
function fadeOutItems(ele, delay) {
var $$ = $(ele), $n = $$.next();
// Toggle the active class
$$.toggleClass('active');
// Ensure the next element exists and has the correct nodeType
// of an unordered list aka "UL"
if ($n.length && $n[0].nodeName === 'UL') {
$('li', $n).each(function(i) {
// Determine whether to use a fade effect or a very quick
// sliding effect
delay ? $(this).stop(true, true).delay(i * 400).fadeToggle('slow') : $(this).stop(true, true).slideToggle('fast');
});
}
}
Since you call this on both the currently active tab and the newly active tab, this should stop any animations underway on the currently active tab.
See the jQuery doc on .stop() for details.
In looking at this code further, I believe it does what you literally asked for in your question (it stops the previous tab looping and starts the next tab), but I'm not sure that's actually what you want because it leaves the items in a tab only partially expanded. If that's what you want, then this will do that.
If that's not what you want, then the code will have to be modified a bit further to not only stop the currently running animations, but to put all the items for the old tab into the same state.
As I suspected, you actually want more than you asked for (per your most recent comments). You want the previously items to be hidden, no matter what state they were in previously. You can do that with this code where I changed the slideToggle() to a slideUp(). You can't use any form of toggle if the animation hasn't started yet because toggle will go the wrong way (it just reverses the state). Instead, when hiding you have to use a definitive animation that ends with the item not visible. You can use this code where I used slideUp() but you could pick something different if you wanted:
// A helper function that allows multiple LI elements to be either
// faded in or out or slide toggled up and down
function fadeOutItems(ele, show) {
var $$ = $(ele), $n = $$.next();
// Toggle the active class
$$.toggleClass('active');
// Ensure the next element exists and has the correct nodeType
// of an unordered list aka "UL"
if ($n.length && $n[0].nodeName === 'UL') {
$('li', $n).each(function(i) {
// Determine whether to use a fade effect or a very quick
// sliding effect
show ? $(this).stop(true, true).delay(i * 400).fadeToggle('slow') : $(this).stop(true, true).slideUp('fast');
});
}
}
You can see that in action here: http://jsfiddle.net/jfriend00/rzd3N/.
The problem is here.
$(this).delay(i * 400).fadeToggle('slow')
You are giving a fede effect to each element at once, by increasing delay.
It's not easy to stop it this way. The correct way to do this is to call a function which will only fade an element at a time. Then this function will be executed again at a given time interval (400 in your case), and fade the next element.
This way, passing a variable to the function, for example stopExecuting=true, will stop the effects.
Take a look at setInterval and setTimeout to achieve this.
I created a relatively small dynamic banner rotation script with icons at the bottom for bringing a particular banner into focus. Firing a mouseenter over a banner pauses the show, but sometimes when I mouseout from my banner, the delay for certain banners gets shortened. I'd even understand if it just happened once, but the delay is then set for that shorter amount of time every time the banner comes back around in the rotation, and often the shortening happens in one other place in the list of banners, as well. Sometimes this can be corrected by an as yet undetermined set of actions. I'm starting to suspect that my logic is catching the loop in the middle somewhere and so the process branches out, runs two loops, which appear to speed up the calling of the showNextBanner function. Not sure how to solve this. I've put in tests to see if it's currently in play mode, to no avail.
I include what I think are the relevant parts of the code below.
var firstRun = true;
var play = true;
var current = 0;
var banners = $$( '.banner' );
banners.invoke( 'hide' );
var images = $$( '.image' );
var icons = $$( '.icon' );
//dynamically clones an initial icon to match the number of banners
initIcons();
banners.invoke( 'observe', 'mouseenter', function( field ) {
play = false;
});
banners.invoke( 'observe', 'mouseleave', function( field ) {
if( !play ) {
play = true;
showNextBanner().delay(3);
}
});
icons.invoke( 'observe', 'click', function( field ) {
play = false;
hideBanner( current );
showBanner( findObj( icons, field.findElement()));
});
showNextBanner().delay(3);
function hideBanner( which ) {
icons[ which ].src = blankIconSRC;
banners[ which ].hide();
}
function showBanner( which ) {
icons[ which ].src = selectedIconSRC;
banners[ which ].show();
current = which;
}
// loops the hiding and showing of icons
// (mouseenter sets play to false)
function showNextBanner() {
if( play ) {
if( !firstRun ) {
if( ++current == banners.length ) current = 0;
var previous = 0;
( current == 0 )? previous = banners.length - 1: previous = current - 1;
hideBanner( previous );
} else {
icons[0].src = selectedIconSRC;
firstRun = false;
}
showBanner( current );
showNextBanner.delay(3);
}
}
}());
After all that, the client wants a jQuery solution so he can have a slide-in effect not available via scriptaculous. So all that work is down the drain. The good news is that I can just use jCarousel, probably, and tweak the stylesheet. Thanks for the help!
I suspect what is happening is that you've got multiple .delay calls stacking up. So you've got one with less than 3 seconds remaining and showNextBanner is called again, setting another delay timer.
As I read the docs, it appears .delay is intended to put gaps in the jquery event pipeline, rather than actually delay function calls. You may benefit from switching to calling setTimeout instead of delay, so that you get a handle to the timeout, which you can then cancel before setting a new timeout (or cancel if play is set to false, then reset when play is true again) This is mentioned in the JQuery docs for .delay
My guess is that since you don't "cancel" the delay()'ed function, they hang around for too long, but they don't do anything when they fire, because play is false. But once play is true again, the all start having an effect again.
You can save the returned value for delay() and cancel the timer by using clearTimeout() with the value.
However, I'd also suggest that you use a single container for all the banners (and maybe put the the icons in there too), and set the mouseenter/mouseleave events on that, rather than on individual banners. Then there's just a single element that'll start/stop the banner rotation. If you also split everything up in specific functions that play and stop the rotation, and one to show a specific banner, you can possibly get a cleaner code structure.
Here's an example (it's just something I put together for fun rather than an edit of your code, so it's quite different. Sorry. But hopefully you can still use for something)