Slider Ignoring If Conditional When Clicked Multiple Times - javascript

I have jQuery slider that slides items through a container div every 5 seconds by animating the left property by 1400px. Once the left property reaches -2800px an if conditional starts resetting the left property while also removing items from the front of the row and appending them to the back of the list, so that the sliding loop continues infinitely. This slider also has left and right buttons that will allow the user to cycle through the images if they would like to.
The problem I have encountered is that if you click the sliders multiple times in quick succession then the left property goes outside of the -2800px boundary set in the if conditional. I am assuming this is because the multiple click events are all fired off before the left property reaches the -2800px. How can I stop this from happening? Is there a function that will stop multiple functions from firing before the first one is complete? Here is a jsFiddle (I changed the widths for displays sake) :
http://jsfiddle.net/25tt5vmp/
My jQuery:
$(document).ready(function () {
var myTimer = setInterval(slide, 5000);
function slide() {
var left = $('#sliderList').css('left');
left = left.substring(0, left.length - 2);
if (left <= -2800) {
$('#sliderList').css('left', '-1400px');
var slide = $('#sliderList li:first');
$('#sliderList').children('li:first').remove();
$('#sliderList').append(slide);
$('#sliderList').animate({ left: "-=1400px" }, "slow", "swing");
}
else {
$('#sliderList').animate({ left: "-=1400" }, "slow", "swing");
}
}
$('#sliderLeft').click(function () {
var left = $('#sliderList').css('left');
left = left.substring(0, left.length - 2);
if (left <= -2800) {
$('#sliderList').css('left', '-1400px');
var slide = $('#sliderList li:first');
$('#sliderList').children('li:first').remove();
$('#sliderList').append(slide);
$('#sliderList').animate({ left: "-=1400px" }, "slow", "swing");
clearInterval(myTimer);
myTimer = setInterval(slide, 5000);
}
else {
$('#sliderList').animate({ left: "-=1400" }, "slow", "swing");
clearInterval(myTimer);
myTimer = setInterval(slide, 5000);
}
});
$('#sliderRight').click(function () {
var left = $('#sliderList').css('left');
left = left.substring(0, left.length - 2);
if (left >= 0) {
$('#sliderList').css('left', '-1400px');
var slide = $('#sliderList li:last');
$('#sliderList').children('li:last').remove();
$('#sliderList').prepend(slide);
$('#sliderList').animate({ left: "+=1400px" }, "slow", "swing");
clearInterval(myTimer);
myTimer = setInterval(slide, 5000);
}
else {
$('#sliderList').animate({ left: "+=1400" }, "slow", "swing");
clearInterval(myTimer);
myTimer = setInterval(slide, 5000);
}
});
});

There is one easy solution. Use a blocking-variable. Generate a variable:
var blockedSlider = false;
Then, set it to true when starting the animation.
On every click, you check, if the blockedSlider is true or false, and only fire the animation if false.
And after your animation is done, set the blockedSlider to false again. That's it.

Related

About "paragraph sliding" in html

I want to achieve such a function as paragraph sliding (I don't know how to explain paragraph sliding)
So I just put it on the website for you to see
(It may take a while to enter)
https://grayraven.tw/
Like this one after another
I tried to write it myself, but there was no response after I wrote it
Below is my code
var mousewheel = (/Firefox/i.test(navigator.userAgent)) ?
"DOMMouseScroll" : "mousewheel";
var IDK = 1
slide.addEventListener(mousewheel,
function (e) {
if (e.wheelDelta > 0 || e.detail < 0) {
IDK + 1
$("html,body").animate({scrollTop: $("#" + IDK ).offset().top}, 1000);
} else {
if(IDK=1){
console.log("NO")
}else{
IDK - 1
$("html,body").animate({scrollTop: $("#" + IDK ).offset().top}, 1000);
}
}
}, false);
If you can tell me how to write, thank you very much
My English is not very good, please forgive me
Did you mean this?
//Set each section's height equals to the window height
$('section').height($(window).height());
/*set the class 'active' to the first element
this will serve as our indicator*/
$('section').first().addClass('active');
/* handle the mousewheel event together with
DOMMouseScroll to work on cross browser */
$(document).on('mousewheel DOMMouseScroll', function (e) {
e.preventDefault();//prevent the default mousewheel scrolling
var active = $('section.active');
//get the delta to determine the mousewheel scrol UP and DOWN
var delta = e.originalEvent.detail < 0 || e.originalEvent.wheelDelta > 0 ? 1 : -1;
//if the delta value is negative, the user is scrolling down
if (delta < 0) {
//mousewheel down handler
next = active.next();
//check if the next section exist and animate the anchoring
if (next.length) {
/*setTimeout is here to prevent the scrolling animation
to jump to the topmost or bottom when
the user scrolled very fast.*/
var timer = setTimeout(function () {
/* animate the scrollTop by passing
the elements offset top value */
$('body, html').animate({
scrollTop: next.offset().top
}, 'slow');
// move the indicator 'active' class
next.addClass('active')
.siblings().removeClass('active');
clearTimeout(timer);
}, 800);
}
} else {
//mousewheel up handler
/*similar logic to the mousewheel down handler
except that we are animate the anchoring
to the previous sibling element*/
prev = active.prev();
if (prev.length) {
var timer = setTimeout(function () {
$('body, html').animate({
scrollTop: prev.offset().top
}, 'slow');
prev.addClass('active')
.siblings().removeClass('active');
clearTimeout(timer);
}, 800);
}
}
});
body, html {
margin:0;
padding:0;
overflow:hidden;
}
section {
height:100vh!important;
font-size:30px;
display:flex;
justify-content:center;
align-items:center;
color:white;
}
.bg1{background-color:#FAAD80;}
.bg2{background-color:#FF6767;}
.bg3{background-color:#FF3D68;}
.bg4{background-color:#A73489;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="bg1">First</section>
<section class="bg2">Second</section>
<section class="bg3">Third</section>
<section class="bg4">Fourth</section>

How do I set auto timer to content slideshow?

I am using the following as a content slider but unsure as to instead have the click the button to play the slides through but wanting to take that away and for the slides to go go through on load?
DEMO
$(document).ready(function() {
var height = 300,
width = 600,
tabs = 3,
$tabs = $('.tab'),
contentNum = 1,
delay = 2000, // time in milliseconds to pause between tabs
timer;
$('.play').click(function(){
var $t = $(this);
if ($t.hasClass('playing')) {
// stop
clearTimeout(timer);
$t.removeClass('playing').html('play');
} else {
// play
timer = setInterval(function(){
contentNum++; // change to contentNum--; to go left
if (contentNum > tabs){ contentNum = 1; } // loop right
if (contentNum < 1) { contentNum = tabs; } // loop left
$tabs.eq(contentNum-1).find('a').trigger('click');
}, delay);
$t.addClass('playing').html('stop');
}
});
$('.main_inner').css({
width: tabs * width
});
$('a.tab_link').click(function() {
$tabs.filter('.active').removeClass('active');
$(this).parent().addClass('active');
// make sure contentNum is a number and not a string
contentNum = parseInt( $(this).attr('rel'), 10 );
$('.main_inner').animate({
marginLeft: '-' + (width * contentNum - width)
}, 600);
return false;
});
});
No really sure what you mean.
If you wan't to autoplay on page load and keep the Play button use
$('.play').trigger('click');
If you wan't to autoplay without play/stop button replace
$('.play').click(function(){
// you current play/pause button code
});
simply by
// play
setInterval(function(){
contentNum++; // change to contentNum--; to go left
if (contentNum > tabs){ contentNum = 1; } // loop right
if (contentNum < 1) { contentNum = tabs; } // loop left
$tabs.eq(contentNum-1).find('a').trigger('click');
}, delay);

How to add if statements to loop the images around?

This code makes the 'li' move like I want to but when I get to the last 'li' and click next it keeps moving and the 'li' moves out of the users view. I want to know how to loop it so the first 'li' shows up again.
<script type="text/javascript">
$(document).ready(function() {
$('#right').click(function() {
$('.carousel-inner li').animate({
right: '+=292px'
}, 500);
});
$('#left').click(function() {
$('.carousel-inner li').animate({
right: '-=292px'
}, 500);
});
});
</script>
Here is a Fiddle to see an example
This should solve your problem:
$(document).ready(function () {
var inner = $('.carousel-inner'),
slides = inner.find('li'),
width = slides.eq(0).outerWidth(true),
max = (width * slides.length) - width;
$('#right, #left').on('click', function () {
var currRight = parseInt(inner.css('right'), 10), move;
if (this.id === 'right') {
move = currRight === max ? 0 : currRight+width;
} else {
move = currRight === 0 ? max : currRight-width;
}
inner.animate({ right: move }, 500);
});
});
The top four lines cache elements and set up a few basic variables such as the max right value that can used and the width of the slides.
I've then combined the click events to avoid repetition. The first line of the click event defines currRight as $('.carousel-inner')'s current CSS right value as well as move which is used later on.
if (this.id === 'right'){ /* #right */ }else{ /* #left */ } checks whether the id of the clicked element is right or left. The code inside the if statement just checks to see whether the slider is at zero (the beginning) or max (the end) and then sets the move variable to the correct value.
Here it is working: http://jsfiddle.net/mFxcq/10/
Update: To make the slides move on a timer add this after the click event is attached:
function setTimer(){
clearTimeout(window.slideTimer);
window.slideTimer = setTimeout(function(){ $('#right').trigger('click'); }, 5000);
};
setTimer();
Then add setTimer(); right after inner.animate({ right: move }, 500); and everything will work as expected.
Here it is working: http://jsfiddle.net/mFxcq/14/
Add a totalItems variable which will represent the total number of items in the carousel, and a currentItem variable which will represent the number of the current item being displayed (i.e. a number from 1 to totalItems). Then, simply check if it's the last item, and if it is, move the position back to the first one. Check out the revised fiddle, where it works in both directions. Here's example JavaScript, with everything written out for clarity.
var totalItems = $('.carousel-inner li').length;
var currentItem = 1;
$('#right').click(function () {
if (currentItem === totalItems) {
// We've reached the end -- go to the beginning again
$('.carousel-inner li').animate({
right: '-=' + 292 * (totalItems-1) + 'px'
}, 500);
currentItem = 1;
} else {
$('.carousel-inner li').animate({
right: '+=292px'
}, 500);
currentItem += 1;
}
});
$('#left').click(function () {
if (currentItem === 1) {
// We're at the beginning -- loop back to the end
$('.carousel-inner li').animate({
right: '+=' + 292 * (totalItems-1) + 'px'
}, 500);
currentItem = totalItems;
} else {
$('.carousel-inner li').animate({
right: '-=292px'
}, 500);
currentItem -= 1;
}
});
Take a look at this fiddle for a working approach. For the right click.
Basically, each time you click "Right", you'll test to compare the distance traveled by the items and compare that to the maximum distance allowed based on the total number of items.
var slideWidth = 292;
$('#right').click(function() {
if(parseInt($('.carousel-inner li').css('right')) == slideWidth*($('.carousel-inner li').length-1)) {
$('.carousel-inner li').animate({
right: '0px'
, 500);
}
else {
$('.carousel-inner li').animate({
right: '+=' + slideWidth + 'px'
}, 500);
}
});

If no mouse over hide

I have a link that shows a div on mouse over.
On mouse out I hide the div again.
Yet, if the user never mouse overs the div after it opens then it stays open so I need to hide the div after a certain time.
Since these are 2 elements (link and a div) I do not think I can use .hover. How would I best write this to hide .tooltip-profile after 10 seconds of no mouse over?
$("#profile").mouseenter(function(){
var position = $(".tooltip-profile").offset();
$(".tooltip-profile").css( { position: "absolute", left: "720px", top: "-110px" } );
$(".tooltip-profile").fadeIn(500);
} );
$(".tooltip-profile").mouseleave(function(){
$(".tooltip-profile").fadeOut(500);
} );
You need to provide a callback function to your fadeIn() which defines a timeout of 10 seconds. When reached, the time out will fadeOut() the element:
$("#profile").mouseenter(function () {
var position = $(".tooltip-profile").offset();
$(".tooltip-profile").css({
position: "absolute",
left: "720px",
top: "-110px"
});
$(".tooltip-profile").fadeIn(500, function () {
setTimeOut(function () {
$(".tooltip-profile").fadeOut(500);
}, 10000);
});
});
$(".tooltip-profile").mouseleave(function () {
$(".tooltip-profile").fadeOut(500);
});
Wait for some time using setTimeout on mouseleave during this time if mouse is again on link or tooltip don't hide tooltip.
var keepOpend ;
$("#profile").mouseenter(function(){ keepOpend = true;
var position = $(".tooltip-profile").offset();
$(".tooltip-profile").css( { position: "absolute", left: "720px", top: "-110px" } );
$(".tooltip-profile").fadeIn(500);
}).mouseleave(function(){
keepOpend = false;
setTimeout(function(){
!keepOpend && $(".tooltip-profile").fadeOut(500);
}, 500);
});
$(".tooltip-profile").mouseleave(function(){
keepOpend = false;
setTimeout(function(){
!keepOpend && $(".tooltip-profile").fadeOut(500);
}, 500);
}).mouseenter(function(){
keepOpend = true;
});

jquery slide back and forth or slide round

Please i need help sliding images using jquery back and forth, or just to go round. right now it slides upto the last element and rushes back to the first div and begins again, not beautiful at all,i know i should call back a function to do that but i keep getting mistakes. thanks in advance, this is my jquery code below
$(document).ready(function() {
var currentPosition = 0;
var slideWidth = 190;
var slides = $('.slider_move');
var numberOfSlides = slides.length;
var slideShowInterval;
var speed = 5000;
slideShowInterval = setInterval(changePosition, speed);
slides.wrapAll('<div id="slidesHolder"></div>')
slides.css({ 'float' : 'left' });
$('#slidesHolder').css('width', slideWidth * numberOfSlides);
function changePosition() {
if(currentPosition == numberOfSlides - 1) {
currentPosition = 0;
} else {
currentPosition++;
}
moveSlide();
}
function moveSlide() {
$('#slidesHolder')
.animate({'marginLeft' : slideWidth*(-currentPosition)});
}
});​
Instead of:
if(currentPosition == numberOfSlides - 1) {
currentPosition = 0;
} else {
currentPosition++;
}
You need to move the first slide to the very end (and adjust the position of the container at the same time):
if (currentPosition > 0) {
$('#slidesHolder').css('marginLeft',0)
.children().first().appendTo('#slidesHolder');
} else {
currentPosition += 1;
}
http://jsfiddle.net/mblase75/qatry/
Or, to optimize the whole thing a little more, you can eliminate the currentPosition variable and the moveSlide sub-function, and just use a callback in the .animate method:
function changePosition() {
$('#slidesHolder').animate({
'marginLeft': 0-slideWidth
}, function() {
$('#slidesHolder').css('marginLeft', 0)
.children().first().appendTo('#slidesHolder');
});
}
http://jsfiddle.net/mblase75/8vaCg/

Categories

Resources