I have a script that I found at http://www.red-team-design.com/cool-notification-messages-with-css3-jquery, but I'm having a problem with my code
I'm wanting to get it to 1) hide on click, and 2) hide after 15 seconds
HTML:
<div class="warning message">It is currently past 4pm. Any orders placed between now and midnight will not be placed until 4pm tomorrow.</div>
Javascript:
var myMessages = ['info','warning','error','success']; // define the messages types
function hideAllMessages(){
var messagesHeights = new Array(); // this array will store height for each
for (i=0; i<myMessages.length; i++){
messagesHeights[i] = $('.' + myMessages[i]).outerHeight(); // fill array
$('.' + myMessages[i]).css('top', -messagesHeights[i]); //move element outside viewport
}
}
function showMessage(type){
hideAllMessages();
$('.'+type).animate({top:"0"}, 500);
setTimeout(function(){
$('.'+type).animate({top: -$('.'+type).outerHeight()}, 500);
hideAllMessages();
},15000);
}
$(document).ready(function(){
// Initially, hide them all
hideAllMessages();
// Show message
for(var i=0;i<myMessages.length;i++) {showMessage(myMessages[i]);}
// When message is clicked, hide it
$('.message').click(function(){
$(this).animate({top: -$(this).outerHeight()}, 500);
});
});
This is getting executed by php, which I'm just inserting the following line into my code using php:
<script type='text/javascript'>
$(document).ready(function(){
showMessage(warning)
});
</script>
Now for some reason the div doesn't hide when I click it, and it won't hide after the 15 seconds as specified.
I've created a JSFiddle at http://jsfiddle.net/dpdesignz/yTaRa/1/ if anyone would mind looking to see what may be going wrong? I have a feeling it's related to the part executed by the PHP echo, so does anyone know of another way to maybe do this?
You have a few errors in your code.
First warning is not defined
Which refers to the following:
$(document).ready(function(){
showMessage(warning)
});
warning is not a set variable. Perhaps you mean this to be 'warning'.
Secondly showMessage is not defined
showMessage('warning');
This is called before the showMessage() function is defined. You can fix this by moving this call into the other $(document).ready()
http://jsfiddle.net/yTaRa/5/
var myMessages = ['info','warning','error','success']; // define the messages types
function hideAllMessages(){
var messagesHeights = new Array(); // this array will store height for each
for (i=0; i<myMessages.length; i++){
messagesHeights[i] = $('.' + myMessages[i]).outerHeight(); // fill array
$('.' + myMessages[i]).css('top', -messagesHeights[i]); //move element outside viewport
}
}
function showMessage(type){
hideAllMessages();
$('.'+type).animate({top:"0"}, 500);
setTimeout(function(){
$('.'+type).animate({top: -$('.'+type).outerHeight()}, 500);
hideAllMessages();
},15000);
}
$(document).ready(function(){
// Initially, hide them all
hideAllMessages();
// Show message
for(var i=0;i<myMessages.length;i++) {showMessage(myMessages[i]);}
// When message is clicked, hide it
$('.message').click(function(){
$(this).animate({top: -$(this).outerHeight()}, 500);
});
showMessage('warning');
});
$(document).ready(function(){
$('.info, .warning, .error, .success').hide();
$('.info, .warning, .error, .success').slideDown(500);
$('.info, .warning, .error, .success').delay(15000).slideUp(500);
$('.info, .warning, .error, .success').on('click', function() {
$(this).hide();
});
});
Let jQuery do all the work =)
http://jsfiddle.net/yTaRa/8/
If every message type will also be classed as message we can reduce this code down even further...
$(document).ready(function(){
$('.message').hide();
$('.message').slideDown(500);
$('.message').delay(15000).slideUp(500);
$('.message').on('click', function() {
$(this).hide();
});
});
http://jsfiddle.net/yTaRa/9/
$(document).ready(function(){
setTimeout(function() { //sets a 15 second timer on each message to collapse up over .5 seconds
$('.message').slideUp(500);
}, 15000);
$('.message').hide(); //hides all elements with the class message.
$('.message').slideDown(500); //animates messages to expand down over .5 seconds
$('.message').on('click', function() { //wires up click event to hide message on click
$(this).slideUp(500);
});
});
http://jsfiddle.net/yTaRa/10/
I had to use setTimeout for the 15 seconds call of slideUp as the click slideUp would not fire with:
$('.message').delay(15000).slideUp(500);
I assume that this is because only one slideUp() call can be scheduled on the same element at one time.
Related
Based on a condition i am assigning a new message to a variable then showing the message using jquery.Now after 2 seconds i want to hide the message and show another new message.The problem is as i am not showing the message into a html div so i am confused how to attain this ?
if(newresp == "success")
{
var newmsg="<img src=\"images/myimg.png\"><span style='color:#00CCFF;font-size:25px;margin-top:2px'> validated!</span>";
var newmsg1="redirecting ......";
$("#status").hide().fadeIn('slow').html(newmsg);
// i want to hide this newmsg now and then show the newmsg1
}
You can use the javascript setTimeout method.
if(newresp == "success")
{
var newmsg="<img src='images/myimg.png'><span style='color:#00CCFF;font-size:25px;margin-top:2px'> validated!</span>";
var newmsg1="redirecting ......";
$( "#status" ).hide().fadeIn( 500 ).html(newmsg).delay( 2000 ).fadeOut( 500 );
setTimeout(function() {
$( "#status" ).hide().fadeIn(500 ).html(newmsg1).delay( 2000 ).fadeOut( 500 );
}, 3000);
setTimeout(function() {
window.location='http://google.com';
}, 6000);
};
Demo
The first SetTimeout delay is 3000 (3 seconds), the sum of time the first message is visible (500+2000+500)
The second SetTimeout delay is 6000 (3''+3'') and then redirects.
not sure about your entire scenario, but here's a quick fiddle to demonstrate the idea.
basically you want to wrap the content in a div or something and give it an id so you can call it specifically
Create new DOM elements like this:
var img = $('<img src=\"images/myimg.png\">');
var span = $('<span style="color:#00CCFF;font-size:25px;margin-top:2px"> validated!</span>');
Then .append() them both to the div and fade it in. You need to wait for the fade to finish like this:
$(selector).fadeIn('slow', function() {
// will be called when the element finishes fading in
});
Then you can say: $('div.status span').html('Your new message');
You can use the jQuery delay function to wait.
So...
$("#status").hide().fadeIn('slow').html(newmsg).delay( 20000 ).fadeOut('slow').delay( 20000 ).html(newmsg1).fadeIn('slow');
This gives a 2 second delay between both. 2000 is milliseconds = 2 seconds
Edit:
Use the setTimeout function instead...
var newmsg="<span style='color:#00CCFF;font-size:25px;margin-top:2px'>Your click is validated!</span>";
var newmsg1="ok";
$("#verify_status").hide().html(newmsg).fadeIn('slow', function(){
setTimeout(function(){
$("#verify_status").hide().html(newmsg1).fadeIn('slow');
}, 2000);
});
I have a function that hides and shows divs on scroll based on pageY position, but I also need the ability to have it automatically hide and show divs in order(only the ones with children), sort of like a fake animated Gif, looping forever.
I tried this:
function autoPlay() {
$('.conP').each(function(){
if ($(this).children().length > 0) {
setInterval(function(){
$(this).show().delay('100').hide();
},300);
}
});
}
which is not returning any errors, but it's not hiding or showing any of the divs with class="conP".
Any suggestions as to what I'm doing wrong/how I could improve this?
try this -
function autoPlay() {
$('.conP').each(function(){
if ($(this).children().length > 0) {
var $that = $(this);
setInterval(function(){
$that.show().delay('100').hide();
},300);
}
});
}
You have an incorrect reference to this in your setInterval closure. Refer to "How this works" in JavaScript Garden.
In your case you should save the reference to this in a variable:
$('.conP').each(function() {
var $element = $(this);
setInterval(function () {
$(element).show().delay('100').hide();
}, 300);
});
Or, better use the first argument passed to each, which is equal to $(this) in this case.
Not sure it's a great idea to run intervals inside loops, but I'm guessing the issue is scope inside the interval function :
function autoPlay() {
$('.conP').each(function(i, elem){
if ( $(elem).children().length ) {
setInterval(function(){
$(elem).show().delay(100).hide();
},300);
}
});
}
I really appreciate all the help guys, I seem to have figured out the animation part:
setInterval( function() {
autoPlay();
},120);
function autoPlay() {
var backImg = $('#outterLax div:first');
backImg.hide();
backImg.remove();
$('#outterLax').append(backImg);
backImg.show();
}
By hiding whichever div is first, and removing it from-then appending it back into-the containing div, and showing the new first div, it animates quite nicely!
I have a fancybox for displaying photos and descriptions of them.
Now it opens fancybox on mouseenter event. It works perfectly with this code:
$('.fancy_link').live('mouseenter', mouseEnter);
function mouseEnter()
{
jQuery(this).fancybox().trigger('click');
return false;
}
But i need to set delay for opening fancybox. How it should work: User moves cursor over a link, after 1 second fancybox should open and display content. If user moves mouse away before waiting 1 second, fancybox should not open.
I have tried JQuery delay() and setTimeout() but both of them are not working properly.
One sec. delay just ignored by both methods.
use setTimeout/clearTimeout...
//binding code...
$('.fancy_link').on('mouseenter',mouseEnter);
$('.fancy_link').on('mouseleave', mouseLeave);
//run when the mouse hovers over the item
function mouseEnter() {
//clear any previous timer
clearTimeout($(this).data('h_hover'));
//get a reference to the current item, for the setTimeout callback
var that = this;
//set a timer, and save the reference to g_hover
var h_hover = setTimeout(function(){
//timer timed out - click the item being hovered
$(that).click();
}, 1000);
//save the reference - attached to the item - for clearing
// data is a generic "store", it isn't saved to the tag in the dom.
// note: if you have a data-* attribute it is readable via data()
$(this).data('h_hover',h_hover)
}
//handler for when the mouse leaves the item
function mouseLeave() {
//clear the previously set timeout
clearTimeout($(this).data('h_hover'));
}
this could help you
function openFancybox() {
setTimeout( function() {$('#fancy_link').trigger('click'); },1000);
}
I imagine you will need to use setTimeout and clearTimeout
Something along these lines:
var timer;
$('.fancy_link').mouseenter(function(){
var $this = $(this);
timer = setTimeout(function(){
$this.fancybox().trigger('click');
}, 1000);
}).mouseleave(function(){
clearTimeout(timer);
});
Try this solution:
var timer = null;
$('.fancy_link').on('mouseenter', function() {
timer = setTimeout(mouseEnter, 1000);
});
// clear timer when mouse leaves
$('.fancy_link').on('mouseleave', function() {
clearTimeout(timer);
});
I'm am attempting to build a homepage that has animations. I am having hard time controlling my animations though. All I need is to hide elements, and then show elements after a certain time. Loop through that sequence, and pause and show all elements when the someone hovers over the box. Example simple animation.
I have a long way to go. At first I tried using the .css() visibility property, now I'm using .show() and .hide().
I need a way to loop through my animations. I attempt to add another
setTimeout(clear1(), 3000);
to the end of my box1 function, but that wouldn't work for some reason.
I need a way to on a user hover over #box1, that all animations stop. I have tried using .clearQueue, but I couldn't get that to work.
First of all, set to your css:
.box {display: none;}
SHOW ALL BOXES ON HOVER See Demo
This will show all boxes on hover and then continue the animation from where it stopped (will hide the boxes that hadn't shown up during the animation). I think that is what you are after.
var index = 0; // To keep track of the last div showed during animation
var time_of_delay = 1000; // Set the time of delay
// Start the animation
$(document).ready(function () {
box1(time_of_delay);
});
// The hover states
$("#box1_1").hover(
function() {
box1(0);
}, function() {
box1(time_of_delay);
});
// The animation function
function box1 (delay_time) {
var time=delay_time;
if(time>0) {
$(".box").slice(index).each(function() {
$(this).hide().delay(time).show(0);
time=time+time_of_delay;
});
index=0;
} else {
$(".box:visible").each(function() {
index++;
});
$(".box").stop(true).show(0);
}
}
PAUSE ON HOVER See Demo
This will only pause the animation and continue from where it stopped.
var time_of_delay = 1000; // Set the time of delay
// Start the animation
$(document).ready(function () {
box1(time_of_delay);
});
// The hover states
$("#box1_1").hover(
function() {
box1(0);
}, function() {
box1(time_of_delay);
});
// The animation function
function box1 (delay_time) {
var time=delay_time;
if(time>0) {
$(".box:hidden").each(function() {
$(this).delay(time).show(0);
time=time+time_of_delay;
});
} else {
$(".box").stop(true);
}
}
I used setTimeout and clearTimeout and periodically call a function that increments (and resets) the box to display. Since I assign setTimout to boxt, I am able to call clearTimeout(boxt) on box1's hover event so that I can stop specifically that loop. Here's my jsfiddle. It might not be the exact effect you're trying to achieve, but it should be the right functionality and be easily adaptable with a few tweaks. Let me know if this works for you and if you have any questions about how it works :)
LIVE DEMO
var $box = $('#box1').find('.box'),
boxN = $box.length,
c = 0,
intv;
$box.eq(c).show(); // Show initially the '0' indexed .box (first one)
function loop(){
intv = setInterval(function(){
$box.eq(++c%boxN).fadeTo(400,1).siblings().fadeTo(400,0);
},1000);
}
loop(); // Start your loop
$('#box1').on('mouseenter mouseleave', function( e ){
return e.type=='mouseenter' ? (clearInterval(intv))($box.fadeTo(400,1)) : loop();
});
Where ++c%boxN will take care to loop your animation using the Modulo % (reminder) operator inside a setInterval. Than all you need to do is to register a mouseenter and mouseleave on the parent element to:
clear the Interval on mouseenter + fade all your elements
restart your loop function on mouseleave.
Here's one way to do it:
// hide all of the boxes
$('.box').hide();
// reference to each box, the current box in this list and a flag to stop the animation
var divs = box1.getElementsByClassName('box');
var i = 0;
var run = true;
// this will animate each box one after the other
function fade(){
if(i < divs.length && run){
$(divs[i++]).fadeIn(500, function(){
setTimeout(fade, 1000);
});
}
};
fade();
// stop the above function from running when the mouse enters `box1`
$('#box1').on('mouseenter', function(){console.log('enter');
run = false;
});
// start the function again from where we stopped it when the mouse leaves `box1`
$('#box1').on('mouseleave', function(){console.log('leave');
run = true;
fade();
});
Demo: http://jsfiddle.net/louisbros/dKcn5/
I have this code which animates between divs sliding out. If an item is clicked, it's relevant content slides out. If another item is clicked, the current content slides back in and the new content slides out.
However,
var lastClicked = null;
var animateClasses = ['ale', 'bramling', 'bullet', 'miami-weisse'];
for (var i=0; i<animateClasses.length; i++) {
(function(animCls) {
$('.each-brew.'+animCls).toggle(function() {
if (lastClicked && lastClicked != this) {
// animate it back
$(lastClicked).trigger('click');
}
lastClicked = this;
$('.each-brew-content.'+animCls).show().animate({ left: '0' }, 1000).css('position','inherit');
}, function() {
$('.each-brew-content.'+animCls)
.animate({ left: '-33.3333%' }, 1000, function() { $(this).hide()}) // hide the element in the animation on-complete callback
.css('position','relative');
});
})(animateClasses[i]); // self calling anonymous function
}
However, the content sliding out once the already open content slides back is sliding out too quickly - it needs to wait until the content has fully slided back in before it slides out. Is this possible?
Here's a link to what I'm currently working on to get an idea (http://goo.gl/s8Tl6).
Cheers in advance,
R
Here's my take on it as a drop-in replacement with no markup changes. You want one of three things to happen when a menu item is clicked:
if the clicked item is currently showing, hide it
if something else is showing, hide it, then show the current item's content
if nothing is showing, show the current item's content
var lastClicked = null;
// here lastClicked points to the currently visible content
var animateClasses = ['ale', 'bramling', 'bullet', 'miami-weisse'];
for (var i=0; i<animateClasses.length; i++) {
(function(animCls) {
$('.each-brew.'+animCls).click(function(event){
if(lastClicked && lastClicked == animCls){
// if the lastClicked is `this` then just hide the content
$('.each-brew-content.'+animCls).animate(
{ left: '-33.3333%' }, 1000,
function() {
$(this).hide();
}).css('position','relative');
lastClicked = null;
}else{
if(lastClicked){
// if something else is lastClicked, hide it,
//then trigger a click on the new target
$('.each-brew-content.'+lastClicked).animate(
{ left: '-33.3333%' }, 1000,
function() {
$(this).hide();
$(event.target).trigger('click');
}).css('position','relative');
lastClicked = null;
}else{
// if there is no currently visible div,
// show our content
$('.each-brew-content.'+animCls).show()
.animate({ left: '0' }, 1000)
.css('position','relative');
lastClicked = animCls;
}
}
});
})(animateClasses[i]); // self calling anonymous function
}
Well, I'm pretty sure there are other more easy possibilities and I didn't have much time but here is a working jsfiddle: http://jsfiddle.net/uaNKz/
Basicly you use the callback function to wait until the animation is complete. In this special case it's the complete: function(){...}
$("document").ready(function(){
$('#ale').click(function(){
if ($('div').hasClass('toggled')){
$('.toggled').animate({ width: "toggle" }, { duration:250, complete: function(){
$('#alecont').animate({ width: "toggle" }, { duration:250 }).addClass('toggled');}
}).removeClass('toggled');
}else{
$('#alecont').animate({ width: "toggle" }, { duration:250 }).addClass('toggled');
}
});
$('#bramling').click(function(){
if ($('div').hasClass('toggled')){
$('.toggled').animate({ width: "toggle" }, { duration:250, complete: function(){
$('#bramcont').animate({ width: "toggle" }, { duration:250 }).addClass('toggled');}
}).removeClass('toggled');
}else{
$('#bramcont').animate({ width: "toggle" }, { duration:250 }).addClass('toggled');
}
});
});
I give a toggled class if a div is expanded. Since the animation on your page seems to be pretty much broken I think this would be a better way to do this. But remember: my code isn't really good. Just fast and it can be refactored. It's working tho..
Rather than using toggles, bind an on "click" handler to your ".each-brew" divs. In the handler, first hide content divs and then show the appropriate content when that animation completes. You can do that with either a promise or a callback. Something like this...
$(".each-brew").on("click", function (event) {
$(".each-brew-content").show().animate({ left: "0" }, 1000, function() {
// Get the brew name from the class list.
// This assumes that the brew is the second class in the list, as in your markup.
var brew = event.currentTarget.className.split(/\s+/)[1];
$(".each-brew-content." + brew).animate({ left: "-33.3333%" }, 1000, function() { $(this).hide(); });
});
});
I think an event and observer would do the trick for you.
set up the callback function on completion of your animation to fire an event.
the listener would first listen for any animation event and after that event is triggered listen for the completion event. when the completion event is fired execute the initial animation event.run method (or whatever you would want to call it)
Within the listener
on newanimationeventtriger(new_anim) wait for x seconds (to eliminate infinite loop poss) while if this lastevent triggers done == true{
new_anim.run();
}