Autostart jQuery slider - javascript

I'm using a script that animates on click left or right to the next div. It currently works fine but I'm looking to add two features to it. I need it to repeat back to the first slide if it is clicked passed the last slide and go to the last slide if click back from the first slide. Also, I'm interested in getting this to autostart on page load.
I've tried wrapping the clicks in a function and setting a setTimeout but it didn't seem to work. The animation is currently using CSS.
Here's the current JS:
<script>
jQuery(document).ready(function() {
var boxes = jQuery(".box").get(),
current = 0;
jQuery('.right').click(function () {
if (current == (-boxes.length + 1)){
} else {
current--;
updateBoxes();
}
console.log(-boxes.length + 1);
console.log(current);
});
jQuery('.left').click(function () {
if (current === 0){
} else{
current++;
updateBoxes();
}
});
function updateBoxes() {
for (var i = current; i < (boxes.length + current); i++) {
boxes[i - current].style.left = (i * 100 + 50) + "%";
}
}
});
</script>
Let me know if I need a jsfiddle for a better representation. So far, I think the code is pretty straightforward to animate on click.
Thanks.

Try
jQuery(document).ready(function () {
var boxes = jQuery(".box").get(),
current = 0,
timer;
jQuery('.right').click(function () {
if (current == (-boxes.length + 1)) {
current = 0;
} else {
current--;
}
updateBoxes();
}).click(); //initialize the view
jQuery('.left').click(function () {
if (current === 0) {
current = -boxes.length + 1;
} else {
current++;
}
updateBoxes();
});
function updateBoxes() {
//custom implementation for testing
console.log('show', current)
$(boxes).hide().eq(-current).show();
autoPlay();
}
function autoPlay() {
clearTimeout(timer);
//auto play
timer = setTimeout(function () {
jQuery('.right').click();
}, 2500)
}
});
Demo: Fiddle

Here's an example based on my comment (mostly pseudocode):
$(function(){
var boxes = $('.box'),
current = 0,
timer;
// Handler responsible for animation, either from clicking or Interval
function animation(direction){
if (direction === 1) {
// Set animation properties to animate forward
} else {
// Set animation properties to animate backwards
}
if (current === 0 || current === boxes.length) {
// Adjust for first/last
}
// Handle animation here
}
// Sets/Clears interval
// Useful if you want to reset the timer when a user clicks forward/back (or "pause")
function setAutoSlider(set, duration) {
var dur = duration || 2000;
if (set === 1) {
timer = setInterval(function(){
animation(1);
}, dur);
} else {
clearInterval(timer)
}
}
// Bind click events on arrows
// We use jQuery's event binding to pass the data 0 or 1 to our handler
$('.right').on('click', 1, function(e){animation(e.data)});
$('.left').on('click', 0, function(e){animation(e.data)});
// Kick off animated slider
setAutoSlider(1, 2000);
Have fun! If you have any questions, feel free to ask!

Related

How can I change slides with scroll event infinitely. Have it working with set interval function, but how to scroll function?

I have this https://codepen.io/mikun/pen/YWgqEX and. Instead of it infinity changing slides, I want it to wait for the scroll event.
I have added this to it but it isn't working the right way.
$('.slide-nav').on('click', function(e) {
e.preventDefault();
// get current slide
var current = $('.flex--active').data('slide'),
// get button data-slide
next = $(this).data('slide');
$('.slide-nav').removeClass('active');
$(this).addClass('active');
if (current === next) {
return false;
} else {
$('.slider__wrapper').find('.flex__container[data-slide=' + next +
']').addClass('flex--preStart');
$('.flex--active').addClass('animate--end');
setTimeout(function() {
$('.flex--preStart').removeClass('animate--start flex--
preStart').addClass('flex--active');
$('.animate--end').addClass('animate--
start').removeClass('animate-
-end flex--active');
}, 800);
}
});
window.onscroll = function Onscrollfunction() {
if (current === next) {
return false;
} else {
$('.slider__wrapper').find('.flex__container[data-slide=' + next
+ ']').addClass('flex--preStart');
$('.flex--active').addClass('animate--end');
}
}

Propagation issue with jQuery button

I have created a javascript / jquery simple game actioned by two buttons.
Button 1: "Play". The game is played ten times, and increments using a variable that I store in local storage. If the increment matches a random number between one and 10, then console.log("match!"), otherwise console,log("no match");
Button 2: "Restart the game". Once the increment is bigger than 10, then the game starts over by clicking the button.
The problem is, if you look into the console, that the second time you play the game, the game jumps by two increments at a time. The third time, by three increments... Why is that? There is a propagation issue here. How do I solve it?
Jsfiddle is here. Code I paste below, as it's very small:
start_game_over()
function start_game_over(event) {
$("#button1").show();
$("#button2").hide();
localStorage.setItem("progress", 0)
$("#button1").on("click", function() {
if (parseInt(localStorage.getItem("progress")) < 11) {
var random_number = Math.floor(Math.random() * (10 - 0) + 0);
console.log(parseInt(localStorage.getItem("progress")));
if (parseInt(localStorage.getItem("progress")) === random_number) {
console.log("match!")
} else {
console.log("no match")
}
localStorage.setItem("progress", parseInt(localStorage.getItem("progress")) + 1);
} else {
$("#button1").hide();
$("#button2").show();
$("#button2").on("click", function() {
start_game_over();
});
}
})
}
When you start_game_over you assign an event listener to the button click, but you never remove it, so when you call the function again it attaches a new one. restructuring the code a bit to handle the clicks outside of that function would be a good idea.
function start_game_over(event) {
$("#button1").show();
$("#button2").hide();
localStorage.setItem("progress", 0)
}
$("#button1").on("click", function() {
if (parseInt(localStorage.getItem("progress")) < 11) {
var random_number = Math.floor(Math.random() * (10 - 0) + 0);
console.log(parseInt(localStorage.getItem("progress")));
if (parseInt(localStorage.getItem("progress")) === random_number) {
console.log("match!")
} else {
console.log("no match")
}
localStorage.setItem("progress", parseInt(localStorage.getItem("progress")) + 1);
} else {
$("#button1").hide();
$("#button2").show();
}
})
$("#button2").on("click", function() {
start_game_over();
});
You are declaring your event listeners inside a function, so every time the function is called, you are creating a new listener. Put them out of the function and the problem is fixed.
You have to clear your $('#button1') event at the end by using $('#button1').off('click');. This will clear the event listener you create every time in your function.
SE doesn't allow localStorage so run this on JSFiddle or local machine.
start_game_over()
function start_game_over(event) {
$("#button1").show();
$("#button2").hide();
localStorage.setItem("progress", 0)
$("#button1").on("click", function() {
if (parseInt(localStorage.getItem("progress")) < 11) {
var random_number = Math.floor(Math.random() * (10 - 0) + 0);
console.log(parseInt(localStorage.getItem("progress")));
if (parseInt(localStorage.getItem("progress")) === random_number) {
console.log("match!")
} else {
console.log("no match")
}
localStorage.setItem("progress", parseInt(localStorage.getItem("progress")) + 1);
} else {
$("#button1").hide();
$("#button2").show();
$("#button2").on("click", function() {
$("#button1").off("click");
$("#button2").off("click");
start_game_over();
});
}
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button1">Play</button>
<button style="display:none" id="button2">Restart the Game</button>
The problem is that each time you invoke start_game_over you are adding additional click handlers to #button1 and #button2. What you want to do is set up the click handlers once and use a function to reset your game state when #button2 is clicked (or just reset the game state in #button2's callback). For example:
var $button1 = $('#button1');
var $button2 = $('#button2');
var start_game_over = function () {
$button1.show();
$button2.hide();
localStorage.setItem('progress', 0)
};
$button1.on('click', function () {
var progress = parseInt(localStorage.getItem('progress'), 10 /*always include radix!*/);
if (progress < 11) {
//... game logic here
} else {
$button1.hide();
$button2.show();
}
});
$button2.on('click', function () {
start_game_over();
});

Starting timer when clicking first card of memory game

Ok I am trying to wrap up a project and the only thing holding me back is it that they call for the timer to start on clicking a match game. The timer starts when the HTML file loads which is not what the project wants and I have tried some methods but ends up freezing the game. I want the timer to be able to start when clicking a card.
var open = [];
var matched = 0;
var moveCounter = 0;
var numStars = 3;
var timer = {
seconds: 0,
minutes: 0,
clearTime: -1
};
//Start timer
var startTimer = function () {
if (timer.seconds === 59) {
timer.minutes++;
timer.seconds = 0;
} else {
timer.seconds++;
};
// Ensure that single digit seconds are preceded with a 0
var formattedSec = "0";
if (timer.seconds < 10) {
formattedSec += timer.seconds
} else {
formattedSec = String(timer.seconds);
}
var time = String(timer.minutes) + ":" + formattedSec;
$(".timer").text(time);
};
This is the code for clicking on a card. I have tried to include a startTimer code into this but doesn't work.
var onClick = function() {
if (isValid( $(this) )) {
if (open.length === 0) {
openCard( $(this) );
} else if (open.length === 1) {
openCard( $(this) );
moveCounter++;
updateMoveCounter();
if (checkMatch()) {
setTimeout(setMatch, 300);
} else {
setTimeout(resetOpen, 700);
}
}
}
};
And this class code I use for my HTML file
<span class="timer">0:00</span>
Try this: https://codepen.io/anon/pen/boWQbe
All you needed to do was remove resetTimer() call from the function that happens on page load and then just do a check in the onClick (of card) to see if the timer has started yet. timer.seconds == 0 && timer.minutes == 0.

jQuery fade in/out between divs

I have this code:
var next = null;
var outer = jQuery('.banner .container');
var current = outer.find('.banner-word:first');
current.fadeIn();
function fade() {
if (current.next('div.banner-word').length > 0) {
next = current.next('div.banner-word');
} else {
next = outer.find('.banner-word:first');
}
current.fadeOut();
next.fadeIn();
current = next;
setTimeout(fade, 11000);
}
// start the process
fade();
A few problems with it - 1) It seems to ignore the first banner-word div 2) On load it shows quickly shows the first 2 banner-word divs and then starts with the second banner-word div
Am I missing something obvious?
Try changing:
if (current.next('div.banner-word').length > 0) {
next = current.next('div.banner-word');
} else {
next = outer.find('.banner-word:first');
}
to:
if (current.next().is('div.banner-word')) {
next = current.next();
} else {
next = outer.find('.banner-word:first');
}
Edit:
try adding a delay to the initial fade() call.
Change
fade();
to
setTimeout(fade, 5000);

How do I display a div when my timer hits zero?

here's my code:
$('#TESTER').hide();
$('#titlehead2').click(
function() {
var doUpdate = function() {
$('.countdown').each(function() {
var count = parseInt($(this).html());
if (count !== 0) {
$(this).html(count - 1);
}
});
};
setInterval(doUpdate,1000);
if(count <= 0) $('#TESTER').show();
}
);
#TESTER is the div I want to display when the timer reaches zero, and #titlehead2 is my play button for the timer. Any help will be much appreciated.
You need to check the value of counter within the timer
$('#TESTER').hide();
$('#titlehead2').click(function () {
var doUpdate = function () {
//need to look whether the looping is needed, if there are more than 1 countdown element then the timer logic need to be revisted
$('.countdown').each(function () {
var count = parseInt($(this).html());
if (count !== 0) {
$(this).html(count - 1);
} else {
$('#TESTER').show();
//you also may want to stop the timer once it reaches 0
clearInterval(timer);
}
});
};
var timer = setInterval(doUpdate, 1000);
});

Categories