Using jQuery to fade in a new image - javascript

Below is the image element that is acting as the background. The position is absolute and it also has a low z-index so it stays behind the rest of the content.
<img src="day-sky.jpg" id="background" />
The secs below just refers to seconds in a minute. This is just for test purposes, but I'd like to have one background image if the seconds is < 30 and a different one if it's greater that 30. If possible the transition would be a nice fade to the next image.
I've been searching around for ways to do this but haven't come up with a good way to do it. Any thoughts?
function changeBackground() {
if (secs > 30) {
//have one background
}
else {
//have a different background
}
}

You might want to use setInterval() function to change the background after every time stamp you define as per your requirement.
setInterval(changebackground, timeout); runs the code/function once after the timeout.
$(function() {
setInterval(function() {
var bg = ["#000","#FF0", "#909"]
var rep= Math.floor(Math.random() *3);
$("body").css("background",bg[rep])
}, 3000)
})

Here's a working example: http://jsfiddle.net/PKqGk/
var imgs = [
"http://placehold.it/1920x1080/&text=1",
"http://placehold.it/1920x1080/&text=2",
"http://placehold.it/1920x1080/&text=3",
"http://placehold.it/1920x1080/&text=4",
"http://placehold.it/1920x1080/&text=5",
"http://placehold.it/1920x1080/&text=6"
],
ind = 0,
dur = 10 * 1000; // ten seconds
(function imgSlide(){
var img = ind % 2 ? $('#imageOne') : $('#imageTwo'),
hid = ind % 2 ? $('#imageTwo') : $('#imageOne');
console.log(img, hid);
img.fadeOut("slow", function(){
hid.fadeIn("slow").css('margin-left', -hid.width()/2);
if (++ind == imgs.length) ind = 0;
img.attr('src', imgs[ind]);
setTimeout(imgSlide, dur);
});
})();​

Related

How do I delay this code running in JavaScript?

I have written this code to change an image:
change = function(){
for (r=0; r<6; r++){
for (i = 0; i < 6 ; i++) {
setInterval(imgfile(number=i+1), 5000);
}
}
}
imgfile= function(number){
a = 'document.getElementById("imgdiv").src = "images/'+number+'.svg"';
eval(a);
}
The function change() is called when a button is clicked.
When I press the button the image changes straight to 6.svg, when I want it to go through the images 1, 2, 3, 4, 5, 6 and to repeat it 6 times. When I change setInterval to change.setInterval or imgfile.setInterval it doesn't work at all. How do I fix this?
change = function(i=0){
imgfile(i%6+1);//change image
if(i<36) setTimeout(change,5000,i+1);//next image in 5 seconds
}
imgfile= function(number){
document.getElementById("imgdiv").src = "images/"+number+".svg";//no need to use ev(i||a)l
}
Instead of loop/interval mess you can simply start a timeout that restarts itself after changing the image... This code will loop over 6 images with a delay of 5 seconds and that 6 times...
Something like this, perhaps?
var index, imgCount, loopCount, imgTag, countdown;
index = 0;
imgCount = 6;
loopCount = 6;
imgTag = document.getElementById('imgdiv');
countdown = function () {
if (index < imgCount * loopCount) {
imgTag.src = 'images/' + index % imgCount + '.svg';
index = index + 1;
setTimeout(countdown, 5000);
}
};
countdown();
Here we're avoiding the double loop and using modular math (index % imgCount) to get the right file number.
For another question I wrote a nice utility function that has quite a number of uses, but can also handle this scenario very easily. The main issue is that there is no time elapsing between the different delays being set. So you are setting 6 different actions to all happen within 5000ms, and all will occur at the same moment.
Here's my original answer
Here's the utility function for that answer, along with its application to your problem.
function doHeavyTask(params) {
var totalMillisAllotted = params.totalMillisAllotted;
var totalTasks = params.totalTasks;
var tasksPerTick = params.tasksPerTick;
var tasksCompleted = 0;
var totalTicks = Math.ceil(totalTasks / tasksPerTick);
var initialDelay = params.initialDelay;
var interval = null;
if (totalTicks === 0) return;
var doTick = function() {
var totalByEndOfTick = Math.min(tasksCompleted + tasksPerTick, totalTasks);
do {
params.task(tasksCompleted++);
} while(tasksCompleted < totalByEndOfTick);
if (tasksCompleted >= totalTasks) clearInterval(interval);
};
// Tick once immediately, and then as many times as needed using setInterval
if (!initialDelay) doTick();
if (tasksCompleted < totalTicks) interval = setInterval(doTick, totalMillisAllotted / totalTicks);
}
// Do 6 actions over the course of 5000 x 6 milliseconds
doHeavyTask({
totalMillisAllotted: 5000 * 6,
totalTasks: 6,
tasksPerTick: 1,
initialDelay: false, // Controls if the 1st tick should occur immediately
task: function(n) { console.log('Set image to "images/' + (n + 1) + '.svg"'); }
});
You want to do setTimeout().
setTimeout pauses for the millesecond value and then does the code. Where setInterval runs the code every whatever milleseconds.
Yeah, don't do change.setInterval or whatever, it is just setInterval.
An example for you would be this inside the for loop to replace the setInterval function.
setTimeout(imgfile(i+1), 5000);

Animation changes the position of div's

Well I've implementes some divs and when I start the page I want them animate, they do, but the problem is that sometimes one div overlaps another one then I see a blank space... How could I avoid this? I'm doing this :
This is how I change the divs :
function swap(d1, d2){
var topaux, leftaux;
topaux = d1.css("top");
leftaux = d1.css("left");
d1.animate({
top: d2.css("top"),
left: d2.css("left"),
}, { duration: 1000, queue: false });
d2.animate({
top: topaux,
left: leftaux,
}, { duration: 1000, queue: false });
}
This is how I'm trying to do it now, but after try this, I didn't have any animation so I had this code and it worked I mean no overlaps between div's....
d1.css("top", d2.css("top"));
d1.css("left", d2.css("left"));
d2.css("top", topaux);
d2.css("left", leftaux);
I call this function (swap) when I'm shuffling the divs as follows :
function swapdivs(){
var i,r, c, d1, d2;
for (i = 1; i < 100; i++) {
r = Math.floor((Math.random() * rows) + 1);
c = Math.floor((Math.random() * columns) + 1);
d1= $("#r"+r+"c"+c);
r = Math.floor((Math.random() * rows) + 1);
c=Math.floor((Math.random() * columns) + 1);
d2 = $("#r"+r+"c"+c);
swap(d1,d2);
}
}
This is the jfiddle
What I'm missing?
Ok, now i see the problem.
In your barrejarPeces function you're scrambling randomly all elements multiple times (100)
for (i = 1; i < 100; i++) {
In the interanvipeces function you try to switch the position of 2 different elements with an animation of 1000ms, calculating their css attributes top and left
Well, the problem is when one (or both) elements are already switching position (since the barrejarPeces function will scramble 100 times without waiting any animation to finish), top and left values won't be correct.
So there are 2 possible solutions:
Don't use animation delay (try to set to 0 instead of 1000 in your fiddle and you'll see it works)
Scramble all elements just once (see my example here, where i changed some logic)

fadeout audio volume on click?

can anyone tell me how can i do this, the callback for volume is like this
Set volume (0%, mute)
Set volume (50%)
Set volume (100%)
and i need to make a single button in jquery, when click a link fadeout sound gradually.
Thank you.
<script>
function fadeOut(callback) {
var volume = 1;
var fade = setInterval(function () {
api_setVolume(players[0], volume);
volume -= .1;
if (volume === 0) {
clearInterval(fade);
if (typeof callback === 'function') {
callback();
}
}
}, 1000);
}
function myCallback() {
// do Something
}
</script>
Fade Out
This is untested but should work. It will reduce the volume by 0.1 every 1 second. You can change the values as you wish.
Here's a function that takes the player whose volume you want to reduce and a fade speed in %/s (that's percent/second) as parameters. In the function I'm assuming api_getVolume(player) is a function in the API you're using.
<script>
function fadeOut(player, fadeSpeed) {
var curVolume = api_getVolume(player),
reductionAmount = curVolume * (fadeSpeed / 1000);
var fadeInterval = setInterval(function () {
var newVolume = curVolume - reductionAmount;
if (newVolume < 0) {
return clearInterval(fadeInterval);
}
api_setVolume(player, newVolume);
curVolume = newVolume;
}, 100);
}
</script>
<!--Example button usage with fade speed of 50%/s (so the fade lasts 2 seconds)-->
<button onclick="fadeOut(player[0], 50);">Next</button>
Here's an explanation for my math for calculating the reductionAmount:
Since the interval is firing every 100 ms, we need to convert the fade speed from %/s to decimal/100ms.
So:
%/s / 10 = %/100ms
then
%/100ms / 100 = decimal/100ms
This decimal is then multiplied by the current volume to obtain the amount of volume to be reduced for each 100 ms interval.

Implementing a timer app in Metro App

I am developing a game in Metro app where there would be an initial timer for the game to run, let's say about 1 minute and 50 seconds and the timer is displaying the current time. if the 1 minute and 50 seconds time is over, the game will be over it will show a message, How would I implement such behaviour?
I would say, you can try this (untested):
remainingTime = 110;
setInterval(function() {
countdownStarted(); // game started
},
milliseconds // game will start in this much time
);
function countdownStarted() {
setInterval(function() {
remainingTime = remainingTime*100;
updateTimeOnScreen(); // after every second
if(remainingTime) countdownStarted();
},
100
);
}
function updateTimeOnScreen() {
if(remainingTime == 0) {
timeUp(); // game over
}
// function continues
}
For more examples, I would suggest you to read this article.
This basically does the trick, though this is the only thing my app does, so your real performance might vary and there are likely other improvements, stylistic and otherwise, you can make:
var timer = setInterval(function () {
var div = document.getElementById('time'); // this is just a div
// the div shows the time like this: "1:20" - 1 minute, 20 seconds
var lastValue = div.innerText.split(':');
var newValue = parseInt(lastValue[0]) * 60 + parseInt(lastValue[1]) + 1;
if (newValue === 110) {
div.innerText = "Game over!";
clearInterval(timer);
} else {
div.innerText = Math.floor(newValue / 60) + ':' + newValue % 60;
}
}, 1000);
For something more robust, check out this article. It looks like it's pretty close to what you want to do.
You can create an object that has a setTimeout and clearTimeout methods set to some user-defined value.
This link can also give you some useful info.

Increment integer by 1; every 1 second

My aim is to create identify a piece of code that increments a number by 1, every 1 second:
We shall call our base number indexVariable, I then want to: indexVariable = indexVariable + 1 every 1 second; until my indexVariable has reached 360 - then I wish it to reset to 1 and carry out the loop again.
How would this be possible in Javascript? - if it makes a difference I am using the Raphael framework.
I have carried out research of JavaScript timing events and the Raphael delay function - but these do not seem to be the answer - can anyone assist?
You can use setInterval() for that reason.
var i = 1;
var interval = setInterval( increment, 1000);
function increment(){
i = i % 360 + 1;
}
edit: the code for your your followup-question:
var interval = setInterval( rotate, 1000);
function rotate(){
percentArrow.rotate(1,150,150);
}
I'm not entirely sure, how your rotate works, but you may have to store the degrees in a var and increment those var too like in the example above.
var indexVariable = 0;
setInterval(function () {
indexVariable = ++indexVariable % 360 + 1; // SET { 1-360 }
}, 1000);
Try:
var indexVariable = 0;
setInterval(
function () {
indexVariable = (indexVariable + 1) % 361;
}, 1000}

Categories

Resources