Using a callback function in jQuery - javascript

I've been breaking my head over this for several hours now, I'm pretty new to javascript overall so please bear with me.
What I'm trying to achieve:
show a 3 seconds div before a video plays (using the Vimeo api)
What I've tried:
I've tried using .setTimeOut, problem is it only fires once, so the video plays for less than a second and then stops.
.setTimeInterval also doesn't work in my case since it fires at an interval and not continuously.
.delay() is only for jquery effects (correct me if I'm wrong)
What I'm trying now; using a callback parameter
I'm trying to add a callback so it fires my second function (in which the video starts) after it did the first function, with the delay(3000)
My code
// SHOW DIV 3 SECONDS BEFORE VIDEO STARTS
(function($) {
$(document).on("click", "a.short-button", function videoStart(callback) {
$('.short_preloader').fadeIn().delay(3000).fadeOut();
callback();
});
// DO THIS FUNCTION AFTER THE DELAY
videoStart(function() {
var vidframe = $('.embed-container.short-embed iframe'),
status = $('.status');
vidframe(function() {
var player = $f(this);
player.api('play');
});
});
})(jQuery);
My function shows the .short_preloader div for 3 seconds, and should fire the second part of the code afterwards.
Thank you so much in advance!
Victor

fadeOut works asynchronously. You need to wait for it to complete and then call the callback function:
Instead of
$('.short_preloader').fadeIn().delay(3000).fadeOut();
callback();
do this:
$('.short_preloader').fadeIn().delay(3000).fadeOut(callback);
See the following example, which works like you want:
$('button').click(function() {
$('.ad').fadeIn().delay(3000).fadeOut(play);
});
function play() {
$('.video').show();
console.log('playing video');
}
.ad, .video {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Start video</button>
<div class="ad">An ad</div>
<div class="video">Video player</div>

Related

Wait before starting JavaScript function

I'm trying to play a sound every time a user gets a new notification. The way I am loading the notifications on my page is simple:
(function($)
{
$(document).ready(function()
{
var $container = $("#noti");
$container.load("notify.php");
var refreshId = setInterval(function()
{
$container.load('notify.php');
}, 1000);
});
})(jQuery);
This works by updating a div container with whatever number the PHP code sends out. it retries every second (probably not the most efficient way, but it works).
I have another piece of code that checks when the div content changes, then creates an alert box (which I will change to playing a sound when the script is done):
var myElement = document.getElementById('noti');
if(window.addEventListener) {
// Normal browsers
myElement.addEventListener('DOMSubtreeModified', contentChanged, false);
} else
if(window.attachEvent) {
// IE
myElement.attachEvent('DOMSubtreeModified', contentChanged);
}
function contentChanged() {
// this function will run each time the content of the DIV changes
alert("js is working");
}
This script works, however it also creates an alert or the first loading of the notifications. This is because it starts of as an empty div, then it loads the data, which sets off this alert script. The only way I could think about going round this is delaying the script from loading for a couple of seconds whilst the AJAX script does its business.
Does anyone know a way I could delay this second script from doing anything for the first few seconds after page load, or perhaps a better way about going round this?
Instead of doing that, use a custom event which you trigger when load finishes:
var refreshId = setInterval(reloadContainer, 1000)
function reloadContainer() {
$container.load('notify.php', function success() {
$container.trigger('loaded')
})
}
$(myElement).on('loaded', contentChanged)

How to Initiate Image Fade Out and Fade In with jQuery Function

I have a little jQuery function in my Asp.Net MasterPage that fades an image out after 3 seconds. It works fine, but I'm having difficulty getting it to fade back in. I've tried several things as I'm new using jQuery, and I know there's something I'm doing or not doing. I can't put my finger on it. Here's what I have:
<script src="/Scripts/jquery-2.1.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function (){
setTimeout(function (){
$('#Image1').fadeOut('slow', function(){
$('#Image1').remove();
});
}, 3000);
});
var fadeBack = function () {
$('#Image1').fadeIn();
};
fadeBack();
</script>
Like I said, it fades out with no problem, but I cannot find the right code structure to bring it back in. I'm thinking maybe an If statement block about the opacity is needed?
The real trick is that I want alternate images in 3 boxes I have as seen here:
I have about 12 images total, and just want them to fade one image out, and bring another in. Being more specific, I mean the following:
Column (1): Image1.FadeOut(); Image2.FadeIn(); Image2.FadeOut(); Image3.FadeIn(), and etc.
So for now, I just need help with how to do this in Column One, and I'll see if can string something together to make the other Columns 2 and 3 follow up. The timing would be 3 second for each.
Lastly, could I use an array to store other images which aren't in the Column One box already and call them into the slideshow fade sequence? I appreciate you help for this knowledge, so I can lock this in mind. Thanks.
Use this code, it will hide the image after 3 seconds and after that 1 sec, it will show image back.
$(document).ready(function (){
setTimeout(function (){
$('#Image1').fadeOut('slow');
}, 3000);
setTimeout(function (){
$('#Image1').fadeIn('slow');
}, 4000);
});
if you want like a slideshow use this code
<div class="yourimg_container">
<img src="http://localhost/app/img/off.png" id="Image1"/>
</div>
/* make an array containing your images path (you can fetch images from database using asp.net/php query)*/
var ss= ["http://localhost/app/img/off.png",
"http://localhost/app/img/on.png",
"http://localhost/app/img/slider.png"];
window.setInterval(function(){
slideshow();
}, 3000);
function slideshow(){
var im=$("#Image1").attr("src");
for(i=0;i<ss.length;i++){
if(ss[i]==im){
if(i==ss.length-1) $('#Image1').attr("src",ss[0]);
else $('#Image1').attr("src",ss[i+1]);
}
}
}
additionally you can use other effects like this
function slideshow(){
var im=$("#Image1").attr("src");
for(i=0;i<ss.length;i++){
if(ss[i]==im){
if(i==ss.length-1) {
$('#Image1').fadeOut(500);
$('#Image1').attr("src",ss[0]);
$('#Image1').fadeIn(700);
}
else {
$('#Image1').fadeOut(500);
$('#Image1').attr("src",ss[i+1]);
$('#Image1').fadeIn(700);
}
}
}
}
Your fadeBack() is launched immediately whereas the fadeOut has 3 sec delay. Set a timer for your fadeBack grater than 3 sec and the img will appear.
There is a function $('#Image1').remove(); Applied. It mean once fade over, the html block will be removed. Then you can't access the object. Because fade in and fade out accessing same id #Image1. So comment the line. It may work.

Delay function after calling in Javascript

I've been having trouble finding any delays right after a function is executed. The problem is that the href loads a little slow and the function takes in effect before the _target page is loaded. You can see the change coming into effect immediately. I'd like to have a little timer to wait a few seconds before the function takes affect.
I've tried setInterval inside a var, but it doesn't seem to be working. setInterval by itself keeps running once the page is clicked and I don't want that. I want the timer to be started once the image is clicked and the link loaded.
<script type='text/javascript'>
function change() {
var image = document.getElementById('doge');
image.src = 'img/doge.png';
document.getElementById("text").innerHTML="<b>such wow</b> much amaze <b><i>very effort</b></i>"
}
</script>
<img src='Logo_256.png' alt='doge' id='doge' onclick='change();'>
<small id='text'>This page was last modified on Wednesday, November 20, 2013 8:43:13 PM</small>
I assure you everything works, so don't mind if the .jpg or .png match up (just edited right now).
Add a timeout to the things that the function does, so the delay occurs when the function runs what you want to happen in your change() function after a setTimeout():
var change = function(){
setTimeout(function() {
var image = document.getElementById('doge');
image.src = 'img/doge.png';
document.getElementById("text").innerHTML="<b>such wow</b> much amaze <b><i>very effort</b></i>"
}, 5000);
};

Image flickering with setInterval() function

I have made a carousel and using JavaScript setInterval() function for rotate image with fixed interval in carousel. Here's the script that I had used:
var timeOut = 4000;
function showSlide() {
//....script for showing image
}
function pauseSlide() {
setInterval(function(){showSlide();}, timeOut);
}
jQuery(document).ready(function() {
pauseSlide();
});
Now the problem is when I have change the browser tab and after few minute back again to carousel browser and what I seen carousel running too faster rather than default time interval, images going to change fast suppose 0 time interval. Please help me with how I can sort this out.
You must get rid of the first interval before starting another, or you start getting more than one interval working simultaneously (i.e. why you start seeing it go "faster")
Do this
var timeOut = 4000;
var interval = 0;
function showSlide() {
//....script for showing image
}
function pauseSlide() {
clearInterval(interval);
interval = setInterval(function(){showSlide();}, timeOut);
}
jQuery(document).ready(function() {
//NOW you can do multiple pauseSlide() calls
pauseSlide();
pauseSlide();
pauseSlide();
pauseSlide();
pauseSlide();
});
From what I know in newer versions of both firefox and chrome, background tabs have setTimeout and setInterval clamped to 1000ms to improve performance. So I think that your issue might relate to that.
Maybe this will help : How can I make setInterval also work when a tab is inactive in Chrome?
Image changing faster than expected may indicate that you have more than one call to pauseSlide(), in one way or another.
Is document ready the only place you call the function ? Any code in showslide or anywhere triggering a document ready event ? If you put an alert() in pauseSlide(), does it popup more than once ?

jQuery: Using a Time Delay in an Each Iterator?

I'm trying to create a carousel effect that automatically cycles through each pictures every 3 seconds.
$(".headline_img").each(function(intIndex){
setTimeout($(this).show(),3000);
});
The timeout delay is not working.
This shows all of the images instantly as soon as the dom loads. It's like its ignoring the setTimeout function.
Did I miss something?
Note: I'm calling this using $(document).ready, do you think that might effect it?
The setTimeout function takes a function reference or a string. Your code calls the show method for each element immediately. I'm not sure if this will work:
$(function () {
var t = 3000, $debug = $('#result');
$(".headline_img").each(function(){
var $img = $(this);
setTimeout($img.show.bind($img), t);
t += 3000;
});
});
.headline_img { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="headline_img">One</div>
<div class="headline_img">Two</div>
<div class="headline_img">Three</div>
but it's worth a try...
You need to change the timeout for each one. Right now, you're attaching the same timeout to all of them at the same time. Something like this should work without changing your code much:
$(".headline_img").each(function(intIndex){
setTimeout($(this).show(),3000 * (intIndex +1));
});
Refactoring to use queue might be more robust in the long term.
Or you can use jQuery's delay function.
$(".headline_img").each(function(intIndex){
$(this).delay(3 * (intIndex + 1)).show();
});

Categories