clearInterval function not actually clearing - javascript

The div completes one round from left to right and right to left scrolling but gets stuck in the scrollBack() function. The program does execute the clearInterval() statement at the desired event but it doesn't actually clear the interval. What am I doing wrong?
var backint = null;
function scrollForward() {
if ($("#foo").scrollLeft() != $("#foo").width()) {
$("#foo").scrollLeft($("#foo").scrollLeft() + 1);
} else {
backint = setInterval(scrollBack, 5);
}
}
function scrollBack() {
if ($("#foo").scrollLeft() != 0) {
$("#foo").scrollLeft($("#foo").scrollLeft() - 1);
} else if ($("#foo").scrollLeft() == 0) {
clearInterval(backint);
}
}

It's better do with
.animate() as Rory McCrossan suggested because that setInterval reimplements existing thing and not necessarily better:
var foo = $("#container"),
bar = $("#foo"),
scrollSize = bar.width() - foo.width();;
function scrollForward() {
console.log('forward', foo.scrollLeft(), bar.width() - foo.width());
if (foo.scrollLeft() != scrollSize) {
foo.animate({
scrollLeft: scrollSize + 'px'
});
}
}
function scrollBack() {
console.log('back', foo.scrollLeft(), scrollSize);
if (foo.scrollLeft() === scrollSize) {
foo.animate({
scrollLeft: '0px'
});
}
}
foo.on("click", scrollForward);
foo.on("dblclick", scrollBack);
#container {
border: 1px solid #ccc;
width: 410px;
overflow-x: scroll;
height: 50px;
}
#foo {
background-color: #ccc;
width: 1300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<div id="foo">Click to scroll right. Double-click to scroll left.</div>
</div>

Related

Javascript click event is doubling every click

Would be really grateful for some advice with this javascript issue I am having with a click event that seems to be doubling every time my slider is closed then reopened.
When you open the slider for the first time and click through the slides you can see in the console the clicks incrementing by 1 every time the 'btn--next' is clicked which is of course correct. When i then close the slider down and re-open it again when the 'btn--next' is clicked the clicks in the console are now incrementing by 2 every click. Close the slider again and re-open and then the 'btn--next' clicks in the console increment by 3 and so on every time the slider is re-loaded.
https://jsfiddle.net/95afhtx8/2/
var loadSlider = document.querySelector('.load__slider');
loadSlider.addEventListener('click', function() {
var slider = document.querySelector('.animal__slider');
var sliderSlide = document.querySelectorAll('.animal__slider__slide');
var nextSlide = document.querySelector('.btn--next');
var previousSlide = document.querySelector('.btn--previous');
var closeSlider = document.querySelector('.animal__slider__close');
var currentSlide = 0;
slider.classList.add('active');
setTimeout(function() {
slider.classList.add('active--show');
startSlide();
}, 100);
//Reset Slider
function resetSlides() {
for (var s = 0; s < sliderSlide.length; s++) {
sliderSlide[s].classList.remove('active--show');
sliderSlide[s].classList.remove('active');
}
}
//Start Slider
function startSlide() {
resetSlides();
sliderSlide[0].classList.add('active');
setTimeout(function() {
sliderSlide[0].classList.add('active--show');
}, 100);
}
//Previous slide
function slidePrevious() {
resetSlides();
sliderSlide[currentSlide - 1].classList.add('active');
setTimeout(function() {
sliderSlide[currentSlide].classList.add('active--show');
}, 100);
currentSlide--;
}
previousSlide.addEventListener('click', function() {
if (currentSlide === 0) {
currentSlide = sliderSlide.length;
}
console.log('click');
slidePrevious();
});
//Next slide
function slideNext() {
resetSlides();
sliderSlide[currentSlide + 1].classList.add('active');
setTimeout(function() {
sliderSlide[currentSlide].classList.add('active--show');
}, 100);
currentSlide++;
}
nextSlide.addEventListener('click', function() {
if (currentSlide === sliderSlide.length - 1) {
currentSlide = -1;
}
console.log('click');
slideNext();
});
closeSlider.addEventListener('click', function() {
slider.classList.remove('active--show');
slider.classList.remove('active');
resetSlides();
});
});
It's because every time you click on your slider toggle:
loadSlider[s].addEventListener('click', function () {
You're re-running code like this, which will add another click handler to the element:
nextSlide.addEventListener('click', function() {
You can add multiple event listeners to any object in the DOM. So you just keep adding more every time the slider opens.
You have three general options here.
Option 1: only set click handlers once
Don't re-add event handlers inside your loadSlider[s].addEventListener('click', function () { function. Do it outside so you aren't re-adding handlers.
Option 2: remove click handlers on close
You can remove the event listeners on close. To do this, you should store a reference to the function you make, so you can explicitly remove it later. You should do this for any handlers you add.
const nextClick = function () {
...
};
nextSlide.addEventListener('click', nextClick);
function resetSlides() {
nextSlide.removeEventListener('click', nextClick);
...
}
This way, when the slider is hidden, the click functionality will be turned off, and re-opening it will add new click handlers and the old ones won't fire because you removed them.
Option 3: Re-create the elements
If you remove an element from the DOM and make a completely new one, the new one won't have stale click handlers on it. This means you'll need to dynamically build your markup with Javascript (using document.createElement), not store it in the HTML page body.
I update your code to work properly (you need to close the anonymous function of the first event listener before you start declaring the others, otherwise you are copying them over and over and therefore the doubling/quadrupling etc...). I would also suggest to move DOM selectors outside of the event listener, they can evaluate only once:
var loadSlider = document.querySelector('.load__slider');
var slider = document.querySelector('.animal__slider');
var sliderSlide = document.querySelectorAll('.animal__slider__slide');
var nextSlide = document.querySelector('.btn--next');
var previousSlide = document.querySelector('.btn--previous');
var closeSlider = document.querySelector('.animal__slider__close');
var currentSlide = 0;
loadSlider.addEventListener('click', function() {
slider.classList.add('active');
setTimeout(function() {
slider.classList.add('active--show');
startSlide();
}, 100);
});
//Reset Slider
function resetSlides() {
for (var s = 0; s < sliderSlide.length; s++) {
sliderSlide[s].classList.remove('active--show');
sliderSlide[s].classList.remove('active');
}
}
//Start Slider
function startSlide() {
resetSlides();
sliderSlide[0].classList.add('active');
setTimeout(function() {
sliderSlide[0].classList.add('active--show');
}, 100);
}
//Previous slide
function slidePrevious() {
resetSlides();
sliderSlide[currentSlide - 1].classList.add('active');
setTimeout(function() {
sliderSlide[currentSlide].classList.add('active--show');
}, 100);
currentSlide--;
}
previousSlide.addEventListener('click', function() {
if (currentSlide === 0) {
currentSlide = sliderSlide.length;
}
console.log('click');
slidePrevious();
});
//Next slide
function slideNext() {
resetSlides();
sliderSlide[currentSlide + 1].classList.add('active');
setTimeout(function() {
sliderSlide[currentSlide].classList.add('active--show');
}, 100);
currentSlide++;
}
nextSlide.addEventListener('click', function() {
if (currentSlide === sliderSlide.length - 1) {
currentSlide = -1;
}
console.log('click');
slideNext();
});
closeSlider.addEventListener('click', function() {
slider.classList.remove('active--show');
slider.classList.remove('active');
resetSlides();
});
.animals {
text-align: center;
position: relative;
width: 80%;
height: 300px;
margin: 0 auto;
background-color: grey;
}
.load__slider {
text-align: center;
}
.animal__slider {
position: absolute;
width: 100%;
height: 100%;
text-align: center;
display: none;
}
.animal__slider.active {
display: block;
}
.animal__slider.active .animal__slider__close {
display: block;
}
.animal__slider.active+.animal__slider__open {
opacity: 0;
}
.animal__slider__slide {
display: none;
position: absolute;
width: 100%;
height: 100%;
}
.animal__slider__slide1 {
background-color: red;
}
.animal__slider__slide2 {
background-color: green;
}
.animal__slider__slide3 {
background-color: yellow;
}
.animal__slider__slide4 {
background-color: blue;
}
.animal__slider__slide.active {
display: block;
}
.btn {
color: black;
position: absolute;
bottom: 5px;
cursor: pointer;
}
.btn--previous {
right: 60px;
}
.btn--next {
right: 30px;
}
.animal__slider__close {
display: none;
position: absolute;
right: 0;
cursor: pointer;
}
.animal__slider__open {
display: block;
cursor: pointer;
}
<section class="animals">
<div class="animal__slider">
Slider
<div class="animal__slider__slide animal__slider__slide1">
slide 1
</div>
<div class="animal__slider__slide animal__slider__slide2">
slide 2
</div>
<div class="animal__slider__slide animal__slider__slide3">
slide 3
</div>
<div class="animal__slider__slide animal__slider__slide4">
slide 4
</div>
<span class="btn btn--previous">previous</span>
<span class="btn btn--next">next</span>
<span class="animal__slider__close">close slider</span>
</div>
<span class="animal__slider__open load__slider">open slider</span>
</section>
In your code, you call nextSlide.addEventListener(...) each time you open the slider, but you never remove that listener. you have to call the function nextSlide.removeEventListener(...) when you close the slider. You also can make sure to call addEventListener only when you open the slider the first time, or even before you open it, as the html element is never destroyed.
To be able to remove the listener, you have to make it accessible in your code when you close the slider. You can't use anonymous functions for this.
EDIT :
An other, simpler solution is to change
nextSlide.addEventListener('click', function(){...});
to:
nextSlide['onclick'] = function() {...};

How to prevent centered text in input button be moved when dynamically changed

I have an input button with a centered text. Text length is changing dynamically with a js (dots animation), that causes text moving inside the button.
Strict aligning with padding doesn't suit because the text in the button will be used in different languages and will have different lenghts. Need some versatile solution. The main text should be centered and the dots should be aligned left to the end of the main text.
var dots = 0;
$(document).ready(function() {
$('#payDots').on('click', function() {
$(this).attr('disabled', 'disabled');
setInterval(type, 600);
})
});
function type() {
var dot = '.';
if(dots < 3) {
$('#payDots').val('processing' + dot.repeat(dots));
dots++;
}
else {
$('#payDots').val('processing');
dots = 0;
}
}
<input id="payDots" type="button" value="Pay" class="button">
.button{
text-align: center;
width: 300px;
font-size: 20px;
}
https://jsfiddle.net/v8g4rfsw/1/ (button should be pressed)
The easiest as this is a value and extra elements can't be inserted, would be to just use leading spaces to make the text appear as it's always centered.
This uses the plugin I wrote for your previous question
$.fn.dots = function(time, dots) {
return this.each(function(i,el) {
clearInterval( $(el).data('dots') );
if ( time !== 0 ) {
var d = 0;
$(el).data('dots', setInterval(function() {
$(el).val(function(_,v) {
if (d < dots) {
d++;
return ' ' + v + '.';
} else {
d = 0;
return v.substring(dots, v.length - dots)
}
})
}, time));
}
});
}
$(document).ready(function() {
$('#payDots').on('click', function() {
$(this).val('Proccessing').prop('disabled',true).dots(600, 3);
});
});
.button{
text-align: center;
width: 300px;
font-size: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="payDots" type="button" value="Pay" class="button">
You can find updated code below
Click Here
HTML Code
<button id="payDots">
<span>Pay</span>
</button>
JS Code
var dots = 0;
$(document).ready(function() {
$('#payDots').on('click', function() {
$(this).attr('disabled', 'disabled');
setInterval(type, 600);
})
});
function type() {
$('button').css('padding-left','100px','important');
var dot = '.';
if(dots < 3) {
$('#payDots').text('processing' + dot.repeat(dots));
dots++;
}
else {
$('#payDots').text('processing');
dots = 0;
}
}
CSS Code
button{
text-align: left;
width: 300px;
font-size: 20px;
position:relative;
padding-left:130px;
}

Javascript- Execute onscroll function after a set timeout

So I am creating a page with three div's which become visible upon scrolling. The problem is that the code makes them all execute at the same time, whereas I want that their should be a time difference between the execution of each onscroll function
Relevant part of code -
HTML
<section id="section2">
<span id="one" class="classbefore">lol</span>
<span id="two" class="classbefore">lol</span>
<span id="three" class="classbefore">lol</span>
</section>
CSS
#section2 > span{
width: 25%;
height: 50%;
position: absolute;
background: #f00;
-webkit-transition: all 0.5s ease;
box-shadow: 1px #000;
}
#section2 > #one{
margin-left: 10%;
}
#section2 > #two{
margin-left: 37.5%;
}
#section2 > #three{
margin-left: 65%;
}
.classbefore{
opacity: 0;
margin-top: 18%;
}
.classafter{
opacity: 1;
margin-top: 20%;
}
Javascript
window.addEventListener('scroll', function (event) {
if (window.scrollY > 600) {
document.getElementById('one').className = "classafter";
} else {
document.getElementById('one').className = "classbefore";
}
}, true);
window.addEventListener('scroll', function (event) {
if (window.scrollY > 600) {
document.getElementById('two').className = "classafter";
} else {
document.getElementById('two').className = "classbefore";
}
}, true);
window.addEventListener('scroll', function (event) {
if (window.scrollY > 600) {
document.getElementById('three').className = "classafter";
} else {
document.getElementById('three').className = "classbefore";
}
}, true);
So, using this, all the three span become visible at the same time. Please suggest a method to give them timeout's so that one function is executed after the other.
Also, can this code be made more efficient ?
I supposed you meant to show them at different times after the same scroll.So what about this?
window.addEventListener('scroll', function (event) {
if (window.scrollY > 600) {
var waitTime = 1000; //base time for showing (in miliseconds)
setTimeout(function () {
document.getElementById('one').className = "classafter";
},waitTime);
setTimeout(function () { //We add time to the others waitings
document.getElementById('two').className = "classafter";
},waitTime + 100);
setTimeout(function () {
document.getElementById('three').className = "classafter";
},waitTime + 200);
} else {
document.getElementById('one').className = "classbefore";
document.getElementById('two').className = "classbefore";
document.getElementById('three').className = "classbefore";
}
}, true);
CODE NOT TESTED !!
Also, because it is the same event, you just need one event listeners, not 3. But that listener will change the class of the elements at diferent times
Also it would be better if you use a loop to iterate through the elements:
window.addEventListener('scroll', function (event) {
var elements = document.getElementsByName("commonName");
if (window.scrollY > 600) {
var waitTime = 1000;//base time for showing (in miliseconds)
for (var i = 0; i < elements.length; i++) {
setTimeout(function () {
elements[i].className = "classafter";
}waitTime + i * 100);
}
} else {
for (var i = 0; i < elements.length; i++) {
elements[i].className = "classafter";
}
}
}, true);
CODE NOT TESTED !!
Then it would be valid for N elements

Make sidebar stop at a certain div

I am trying to get the sidebar to stop below the pink categories bar 20px above the Popular Posts div. Currently, the code below stops the sidebar at the very top div in the sidebar. Is there a way I can alter this code so it stops at the last div (Popular Posts) instead?
JavaScript
/*cache jQueries for performance*/
var
$archiveTitle = jQuery ("#archive-title");
$content = jQuery ("#content"),
$categoriesBar = jQuery ("#categories-bar"),
$loadMore = jQuery ("#load-more"),
$footer = jQuery ("#footer-menu"),
$sidebar = jQuery ("#sidebar"),
$window = jQuery (window),
doSidebarAdjust = false; // only do sidebar adjustments if the DOM is stable
function isMasonryPage () {
return $loadMore.length > 0;
}
function isMasonryStable () {
return $loadMore.hasClass ("disabled");
}
function isSidebarAbove (threshold) {
return $window.scrollTop () >= threshold;
}
function isSidebarBelowFooter () {
var
categoriesBottom = $categoriesBar.offset().top + $categoriesBar.height(),
sidebarHeight = $sidebar.height (),
footerTop = $footer.offset().top;
return categoriesBottom + sidebarHeight + 50 >= footerTop;
}
function canAdjustSidebar () {
/* Determine if there's room to adjust sidebar */
var
archiveTitleHeight = $archiveTitle.length === 1 ?
$archiveTitle.outerHeight() : 0;
answer = $content.height () - 50 >
($sidebar.outerHeight () + archiveTitleHeight);
return answer;
}
function adjustSidebar (threshold) {
if (isMasonryPage ()) { // can lock to top
if (isMasonryStable ()) { // can lock to top or bottom
if (isSidebarBelowFooter ()) {
$sidebar.removeClass ("fixed").addClass ("bottom");
} else if (isSidebarAbove (threshold)) {
$sidebar.addClass ("fixed").removeClass ("bottom");
} else {
$sidebar.removeClass ("fixed");
}
} else { // masonry not stable but can lock to top
if (isSidebarAbove (threshold)) {
$sidebar.addClass ("fixed");
} else {
$sidebar.removeClass ("fixed");
}
}
} else if (canAdjustSidebar ()) { // not a masonry page but sidebar adjustable
if (isSidebarBelowFooter ()) {
$sidebar.removeClass ("fixed").addClass ("bottom");
} else if (isSidebarAbove (threshold)) {
$sidebar.addClass ("fixed").removeClass ("bottom");
} else {
$sidebar.removeClass ("fixed bottom");
}
}
}
if (jQuery(document.body).hasClass("home")) {
jQuery (window).scroll(function () { adjustSidebar (654); });
} else if (jQuery(document.body).hasClass("single") || jQuery(document.body).hasClass("page")) {
jQuery (window).scroll(function () { adjustSidebar (20); });
} else {
jQuery (window).scroll(function () { adjustSidebar (183); });
}
</script>
HTML
<div id="wrapper">
<div id="container">
<div id="content">
<div id="sidebar"></div>
<div id="masonry"></div>
</div>
</div>
</div>
<div id="footer"></div>
CSS
#sidebar {
margin: 0;
right: 0;
width: 220px;
}
#sidebar.fixed {
margin-left: 720px;
position: fixed;
right: auto;
top: 173px;
}
#sidebar.bottom {
bottom: 0;
top: auto;
position: absolute;
}
Did you try to change the position fixed to relative of the sidebar?

Two consecutive Animation will not run in jQuery

please see this script:
<style type="text/css">
.div1
{
background-color: Aqua;
width: 400px;
height: 30px;
}
.div2
{
background-color: Fuchsia;
width: 400px;
height: 30px;
}
.div3
{
background-color: Green;
width: 400px;
height: 30px;
}
.div4
{
background-color: Orange;
width: 400px;
height: 30px;
}
</style>
<script type="text/javascript">
$(document).ready(function () {
var timer = setInterval(showDiv, 2000);
var counter = 0;
function showDiv() {
if (counter == 0) { counter++; return; }
$('div.My').css('height', '30px');
$('div.My').animate({ height: '30' }, 2000, function () { alert('i'); });
$('div.My')
.stop()
.filter(function () { return this.id.match('div' + counter); })
.animate({ height: '50' }, 500, function () { });
counter == 4 ? counter = 0 : counter++;
}
});
</script>
<body>
<div>
<div class="div1 My" id="div1">
</div>
<div class="div2 My" id="div2">
</div>
<div class="div3 My" id="div3">
</div>
<div class="div4 My" id="div4">
</div>
</div>
</body>
I want every 5 second my div become large and then become normal and next div become large.The problem is first animation does not run and just second animation run.Where is the problem?
JSFiddle Sample
Edit 1)
I want when next div become large previous div become normal concurrently.Not previous become normal and then next become large
Check out my fork of your fiddle and let me know if this is doing what you want. You had a call to .stop() in the middle there, which was blocking the slow shrinking animation from displaying.
Now the full script is:
$(document).ready(function () {
var timer = setInterval(showDiv, 2000);
var counter = 0;
function showDiv() {
if (counter == 0) { counter++; return; }
$('div.My').animate({ height: '30px' }, { duration: 500, queue: false });
$('div.My')
.filter(function () { return this.id.match('div' + counter); })
.animate({ height: '50px' }, { duration: 500, queue: false });
counter == 4 ? counter = 0 : counter++;
}
});
Edit - new Fiddle
I didn't feel right about the above code, and it didn't work as expected in my browser, so I found a different approach that I think works more cleanly. This one uses jQuery's step option. I also use addClass and removeClass as a kind of local storage to remember which div needs to be shrunk on the next animation. You could do some math with counter and get the same result, but this works.
$(document).ready(function () {
var timer = setInterval(showDiv, 2000);
var counter = 0;
function showDiv() {
if (counter == 0) { counter++; return; }
$shrinker = $("div.big").removeClass("big");
$grower = $("#div"+counter);
$grower
.animate({ height:50 },
{duration:500,
step: function(now, fx) {
$shrinker.css("height", 80-now);
}
}
);
$grower.addClass("big");
counter == 4 ? counter = 0 : counter++;
}
});
The step body looks a bit weird, but it guarantees that at each moment of the animation, the total height of the div stack remains constant. Basically, the total height of the shrinking and growing divs (min:30, max:50) has to be 80 at all times, so the height of the shrinking div should be 80 - the height of the growing div.

Categories