build slider using jquery & javascript - javascript

I built slider using jquery but it is very stupid. You can see it:
http://jsfiddle.net/Bf2Mv/
i think the problem is here:
$(".img img").fadeOut().attr("src", images[count % images.length]).fadeIn();
$(".text").fadeOut().html(text[textcount % text.length]).fadeIn();
how to fix the effects?
thanks a lot!

You probably wanted something like this:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/Bf2Mv/7/
count = 0,
text = [
"first img desc",
"2nd img desc",
"3rd img desc"],
imageCount = images.length,
rand = 6000;
function slide() {
changeImage(1)
rand = 6000;
}
function changeImage(delta) {
count += delta;
if (count < 0) count = imageCount - 1;
count %= imageCount;
$(".img img").fadeOut(function () {
$(this).attr("src", images[count]).fadeIn()
});
$(".text").fadeOut(function () {
$(this).html(text[count]).fadeIn();
});
}
(function loop() {
setTimeout(function () {
slide();
loop();
}, rand);
}());
$("#next").click(function () {
changeImage(1);
});
$("#prev").click(function () {
changeImage(-1);
});
Notes:
You only need a single counter if the images and text arrays are the same length.
You did not need to have modulus operators everywhere if the indexes are managed correctly (between 0 and length-1)
You need to correctly wrap around from 0 to length-1 and back the other way.
You need to change the images after they fadeout (hence the new callbacks in fadeout)
I refactored the change code, so it just takes a direction delta value. That way the same code can be reused by the timer, the next and the prev options.

The problem was on how the fadein/fadeout was defined. You need to use the jQuery fadein/fadeout finished parameter function.
$(".img img").stop().fadeOut('fast', function() {
var that = $(this);
that.attr("src", images[count]).fadeIn('fast', function() {
if (!LOOP_INTERVAL) {
startLoop(); // Continue the loop.
}
});
});
There were also some other issues on the indexes. Here's the solution: http://jsfiddle.net/Bf2Mv/45/
I hope this is what you meant. If you have questions about the answer, feel free to ask!

Related

While MouseDown, first slowly decrease number, then increase decreasing speed (jQuery)

As the title suggests I'm stuck with a MouseDown problem.
What I want in "pseudocode"
While ("#arrowUp").mouseDown(function() {
counter++; //One time directly when pressed
if(MouseDownTime > 500){ //500ms that is
setTimeOut({counter++}, 75); //Meaning, every 75ms counter++
}
}
I have been looking around at Stack Overflow for over two days now. And I succeeded to increment every 75ms, but then I couldn't build in the if(MouseDownTime > 500)-statement, while still being able to increase the counter every 75ms after the 500ms.
$("#tempUp").mousedown(function() { //When longer pressed, automatically faster increase Temperature
int = setInterval(editTemp(currTemp+1), 250);
})
.mouseup(function() {
clearInterval(int);
numberOfRepeats = 0;
});
This is code I have of of my function so far. Could anyone help me out? Or am I asking the question in a wrong way? (non-constructive)
If I understand you correctly you can make use of a combination of setTimeout and setInterval, like so:
$(document).ready(function ()
{
var temp = 0;
var to = null;
var iv = null;
$("#ClickMe").on("mousedown", function ()
{
temp++;
$("#Temp").html(temp);
to = setTimeout(function ()
{
iv = setInterval(function ()
{
temp++;
$("#Temp").html(temp);
}, 75);
}, 500);
}).on("mouseup mouseleave", function ()
{
clearTimeout(to);
clearInterval(iv);
});
});
See this FIDDLE for an example.
EDIT: Added the mouseleave event as well as suggested by José F. Romaniello.

Multiple Timers in Quiz with jQuery

I'm on a quiz, where you can pick an answer out of four answer possibilities (like who wants to be a millionaire). I want to add a counter of 7secs per question to it, if the counter ends, a button to the next question should appear.
I already have my basic code with jQuiz, but my problem is now, that I use always the same counter instance. So the timer of the first question is fine, but if you answer the next question and have some time left of the first one, both counters are displayed at the same time. I think my problem will be solved when I have multiple timer instances, but I don't know how to do this.
Here my code. Sorry about the bad structure, I'm a jQuery newbie.
$('.btn, .nxt').click(function(){
$(this).addClass("checked");
next(this);
var el = $('#progress');
el.width(el.width() + 116 + 'px');
});
function next(elem){
$(elem).parents('.questionContainer').fadeOut(300, function(){
var interval = window.setInterval(function() {
var counter = 0;
clearInterval(interval);
});
var counter = 0;
timer();
$(elem).parents('.questionContainer').next().fadeIn(300);
$('.nxt').hide();
});
};
function timer(){
var counter = 7;
var interval = window.setInterval(function() {
counter--;
$(".counter").html(counter);
if (counter == 0) {
$(".counter").html('');
$('.nxt').show();
clearInterval(interval);
}
}, 1000);
};​
I'm new at Stackoverflow and it's too hard for me to edit code in this textarea... Added fixed JS to jsfiddle.
Try to add your HTML to the same fiddle and test JS, hope it would work.
There are some fixes about structure (caching selections mostly) and added array for timers (with comments) you were asking for.
It'll be easier to debug when you add HTML :)
var quizObj = {
quizTimers: [], //timers array
$counter: $(".counter"),
$buttons: $('.btn, .nxt'),
$progress: $('#progress'),
next: function(elem){
$(elem).parents('.questionContainer').fadeOut(300, function(){
//clears the FIRST timer id in the timers array and removes it from array
clearInterval(quizObj.quizTimers.shift());
quizObj.timer();
$(elem).parents('.questionContainer').next().fadeIn(300);
$('.nxt').hide();
});
},
timer: function() {
var counter = 7;
var interval = window.setInterval(function() {
counter--;
$(".counter").html(counter);
if (counter == 0) {
$(".counter").html('');
$('.nxt').show();
clearInterval(interval);
}
}, 1000);
quizObj.quizTimers.push(interval);
}
}
quizObj.$buttons.click(function(){
$(this).addClass("checked");
quizObj.next(this);
quizObj.$progress.width(quizObj.$progress.width() + 116 + 'px');
});

How to make this a slow jQuery counter

I am currently busy with making a new website.
I would like to make a counter on my website that shows visitors how many websites I made.
I am currently using Javascript and jQuery to do this. The only problem is that while using the for loop, the result shows very fast and I would like it to count up slowly. This is the code I have so far:
$(document).ready(function() {
var websites = 10;
for (var i=0;i<websites;i++)
{
$('.webcounter').html(i);
}
});
Any one has an idea to making the counter go slow?
You can try this:
var interval = window.setInterval(func, delay[, param1, param2, ...]);
This timer works in seconds, you can put the code to run after it's complete in the else section:
Javascript
function countdown(count){
$('.webcounter').html(count);
count -= 1;
if(count >= 0)
setTimeout("countdown("+count+")", 1000);
else
alert("Countdown Complete");
}
$(document).ready(function() {
countdown(10);
}
HTML
<div class="webcounter">Webcounter Holder</div>​
Demo
http://jsfiddle.net/silver89/SBXAQ/8/
Use setInterval:
EXAMPLE
HTML
​<div class="websites">0</div>​​​​​​​​​​​​​​​​​​​​​​​​​​​
JQUERY
$(document).ready(function() {
var websites = 10;
var counter = 1;
var id = setInterval(function(){
$('.websites').text(counter);
counter++;
if(counter > websites){ clearInterval(id);}
}, 500);
});​
Just a quick guess, but try something like this (i'm at work and cant test myself, heheh)
var websites = 10, tmrSiteCount;
function siteCount(i) {
if (i <= websites) {
$('.webcounter').html(i);
tmrSiteCount = setTimeout(function() { siteCount(i++); }, 1000);
}
else {
clearTimeout(tmrSiteCount);
};
}
$(document).ready(function() {
tmrSiteCount = setTimeout(function() { siteCount(1); });
})

jQuery fade image loop

I want to make a loop in my function so that the slideshow effect always restarts.
Here's my fiddle : http://jsfiddle.net/Be67B/
It's all good for the image 1 to go to image 2, but I want it to fade it back to the image 1, and then go the image 2, and so on...to always loop like that.
What do I need to add in my code to make this work?
Don't use a loop, just ask the browser to repetitively call your animation step :
setInterval(function(){
// your animation (in fact just a step)
}, someDelay);
Demonstration : http://jsfiddle.net/dystroy/nPh6S/
In this precise case, the animation is done with :
setInterval(function(){
$("#top").fadeOut(function() {
$(this).attr("src","http://1.bp.blogspot.com/-cFt5KNrHsHc/TZMH6XUBu-I/AAAAAAAAAR4/R6hOP7lffx0/s1600/apple-logo.png").fadeIn().delay(1000).fadeOut(function(){
$(this).attr('src', 'http://coreldrawtips.com/images/applebig.jpg').fadeIn().delay(1000);
});
}
);
}, 4000);
see this jquery cycle plugin:
http://jquery.malsup.com/cycle/
may be this is what you want
You can create a function that does the transition, which has a callback function as part of the fadeIn method that will call back to itself to trigger the next transition, and it would just be in a constant loop.
Here's your modified jsfiddle:
http://jsfiddle.net/Be67B/1/
HTML:
<img id="top" src="http://coreldrawtips.com/images/applebig.jpg" width="300" height="300" />​
Javascript:
$(document).ready(function(){
transition(false);
});
function transition(first)
{
var src = first ? "http://coreldrawtips.com/images/applebig.jpg" : "http://1.bp.blogspot.com/-cFt5KNrHsHc/TZMH6XUBu-I/AAAAAAAAAR4/R6hOP7lffx0/s1600/apple-logo.png";
$("#top").delay(1000).fadeOut(function() {
$(this).attr("src",src).fadeIn(function() {
transition(!first);
});
});
}
​
I just made this code:
$(document).ready(function(){
// images in the pool
var images=["http://1.bp.blogspot.com/-cFt5KNrHsHc/TZMH6XUBu- I/AAAAAAAAAR4/R6hOP7lffx0/s1600/apple-logo.png",
"http://1.bp.blogspot.com/-cFt5KNrHsHc/TZMH6XUBu-I/AAAAAAAAAR4/R6hOP7lffx0/s1600/apple-logo.png"];
// next image to display
var next = 0;
// interval beetween images
var INTERVAL = 1000;
// main function
var doCarrousel = function() {
$("#top").fadeOut(function() {
$(this).attr("src", images[next]).fadeIn(
function() {
setTimeout(doCarrousel, INTERVAL);
});
});
if (++next >= images.length)
next = 0;
};
//start carrousel
doCarrousel();
});
fiddler: http://jsfiddle.net/Be67B/
I would use a plugin. But you can do it by hand. I just recommend against changing the src of the images, because some browsers don't handle it very well, like safari not firing load event.
Instead, have all images inside a container, and cycle their visibility:
$(document).ready(function(){
var currentImage = $("#images img:first");
setInterval(function(){
currentImage.fadeOut();
if(currentImage.next().size())
currentImage = currentImage.next();
else
currentImage = currentImage.siblings().first();
currentImage.fadeIn();
}, 1000)
});
See fiddle: http://jsfiddle.net/Be67B/2/
Quick and dirty: jsFiddle example
function swap(img) {
img = (img == 'http://coreldrawtips.com/images/applebig.jpg') ? 'http://1.bp.blogspot.com/-cFt5KNrHsHc/TZMH6XUBu-I/AAAAAAAAAR4/R6hOP7lffx0/s1600/apple-logo.png' : 'http://coreldrawtips.com/images/applebig.jpg';
$('#top').delay(2000).fadeOut(function() {
$(this).attr('src', img)
}).fadeIn(function() {
setTimeout(function() {
swap(img)
}, 1000);
});
};
swap($('#top').attr('src'));​

Javascript, local copying of a variable's value... struggling to achieve it

I have what i thought was a simple javascript / jquery function (fade out of one div, fade into another... loop until it reaches a maximum and then start back from the begining. The problem i have though is that to fadein the next div i need to increment the global counter. Doing this increments double increments it because i'm assuming the local variable i've created maintains the same reference to the global variable.
The code sample below should explain a little easier. Can anyone spot what i'm doing wrong?
var current_index = 1;
$(document).ready(function() {
$(function() {
setInterval("selectNextStep()", 3000);
});
});
function selectNextStep() {
$("#step_"+current_index).fadeOut('slow', function() {
var next = current_index;
next = next + 1;
$("#step_"+next).fadeIn('slow', function() {
if (current_index == 4) current_index = 1;
else current_index ++;
});
});
}
I think you're ending up with race conditions due to the interval trying to fade things in and the callbacks trying to fade things out. For this setup it makes more sense to let the fade callbacks start the next round.
Also using a 0-based index makes the math easier.
var current_index = 0; // zero indexes makes math easier
$(document).ready(function () {
$(function () {
// use timeout instead of interval, the fading callbacks will
// keep the process going
setTimeout(selectNextStep, 3000);
});
});
function selectNextStep() {
// +1 to adapt index to element id
$("#step_" + (current_index + 1)).fadeOut('slow', function () {
var next = current_index + 1;
// keeps index in range of 0-3
next = next % 4; // assuming you have 4 elements?
current_index = (current_index + 1) % 4;
// callback will start the next iteration
$("#step_" + (next + 1)).fadeIn('slow', function () {
setTimeout(selectNextStep, 3000);
});
});
}
demo: http://jsbin.com/exufu
I do not see any double increment the way your code is..
the problem is that the next variable goes beyond the 4 value that seems to be the limit, and trying to fadein an element that does not exist. so the code that resets the currentIndex never executes..
try adding if (next > 4 ) next = 1; after increasing the next variable
Example at http://jsfiddle.net/5zeUF/
isn't $(function() {}); the same as $(document).ready(function(){}), so you are initializing selectNextStep twice (hence the double increment)?
Try this. Simplifies things a little. Increments (and resets if needed) the current_index before the next fadeIn().
Example: http://jsfiddle.net/r7BFR/
var current_index = 1;
function selectNextStep() {
$("#step_" + current_index).fadeOut('slow', function() {
current_index++;
if (current_index > 4) current_index = 1;
$("#step_" + current_index).fadeIn('slow');
});
}
$(document).ready(function() {
setInterval(selectNextStep, 3000);
});
EDIT: Added example, and fixed my misspelling (camelCase) of current_index.
Here's an alternate way of doing the increment:
current_index = (current_index % 4) + 1;
Try this, slightly different approach but does what you need it to do I believe, also you can add more steps without modifying the script and doesn't pollute the global namespace (window)
[HTML]
​<div class="step defaultStep">One</div>
<div class="step">Two</div>
<div class="step">Three</div>
<div class="step">Four</div>
<div class="step">Five</div>
[CSS]
.step { display: none; }
.defaultStep { display: block; }​
[JS]
$( function() {
var steps = $( ".step" );
var interval = setInterval( function( ) {
var current = $( ".step" ).filter( ":visible" ), next;
if( current.next( ).length !== 0 ) {
next = current.next( );
} else {
next = steps.eq(0);
}
current.fadeOut( "slow", function( ) {
next.fadeIn( "slow" );
} );
}, 3000);
} );
Maybe you also want to have a look at the cycle plugin for jquery. There you can actually achieve such nice transitions. I think with a little work this would ease up everything.
http://jquery.malsup.com/cycle/
Regarding your code snippet. I think you can enhance it a little in this way:
$(document).ready(function() {
var current_index = 0;
window.setInterval(function() {
$("#step_"+ current_index).fadeOut('slow', function() {
$("#step_" + (current_index + 1)).fadeIn('slow', function() {
current_index = (current_index + 1) % 4;
});
});
}, 3000);
});
This should do the exact same work. As the interval function closes over the current_index variable it should be valid inside the function. Sorry, if you're not a fan of all these closures but I rather preferr passing the function I want to execute directly to the setInterval function, than defining it anywhere else.
P.S. Be aware that the changes I introduced imply that your #step_ IDs start at 0.

Categories

Resources