transitionend method to animate a infinite slider with vanilla Javascript - javascript

I'm new to this community and first of all, I take this opportunity to thank all of you for the wonderful work you do every day.
I'm trying to create an infinite manual carousel, in the Netflix style, this is the link to the codepen of everything I have done so far:
https://codepen.io/A12584r/pen/OjvWYp?fref=gc
Here is the relevant javascript:
let prendiContenitoreGalleria = document.querySelector('.contenitore-galleria'),
prendiArticle = Array.prototype.slice.apply(document.querySelectorAll('.contenitore-galleria__article')),
contaArticle = prendiArticle.length,
prendiImmagini = Array.prototype.slice.apply(document.querySelectorAll('.contenitori__img')),
prendiFrecciaSinistra = document.querySelector('.freccia-sinistra'),
prendiFrecciaDestra = document.querySelector('.freccia-destra');
prendiContenitoreGalleria.style.width = 100 * contaArticle + '%';
for (let numeroImmagini = 0; numeroImmagini < prendiImmagini.length; numeroImmagini++) {
prendiImmagini[numeroImmagini].style.width = 100 / contaArticle + '%';
}
prendiContenitoreGalleria.insertBefore(prendiArticle[contaArticle - 1], prendiArticle[0]);
prendiContenitoreGalleria.style.marginLeft = '-' + 100 + '%';
function andareADestra () {
prendiContenitoreGalleria.style.marginLeft = '-' + 200 + '%';
prendiContenitoreGalleria.style.transitionDuration = '.7s';
prendiContenitoreGalleria.addEventListener('transitionend', function(e) {
prendiContenitoreGalleria.appendChild(prendiArticle[0]);
prendiContenitoreGalleria.style.marginLeft = '-' + 100 + '%';
}, false);
}
function andareASinistra () {
prendiContenitoreGalleria.style.marginLeft = 0;
prendiContenitoreGalleria.style.transitionDuration = '.7s';
prendiContenitoreGalleria.addEventListener('transitionend', function(e) {
prendiContenitoreGalleria.insertBefore(prendiArticle[contaArticle - 1], prendiArticle[0]);
prendiContenitoreGalleria.style.marginLeft = '-' + 100 + '%';
}, false);
}
prendiFrecciaSinistra.addEventListener('click', function () {
andareASinistra();
});
prendiFrecciaDestra.addEventListener('click', function () {
andareADestra();
});
I have tried to use the vanilla Javascript transitionend events and what I want to achieve is that when clicking on the right arrow of the carousel the first article is put in place of the third and vice versa, when clicking on the left arrow of the carousel the last article is put in place of the first one.
For this purpose I use marginLeft to move between the articles in my carousel which are 3 and the divs that contains them (these are 3 too) has a width of 300% set via JavaScript.
My problem is that when I click on the carousel arrows, the transition is done but it does a strange effect coming back to its original location immediately.
Any one of you could help me to figure out where I'm wrong and how can I fix it?

In your two functions to move left and right, andareASinistra and andareADestra you are adding an event listener for the transitionend event.
The handler for this is removing the margin-left offset by resetting it to -100% after each move left or right.
You can confirm this is the problem by editing the inline style of the id="contenitore-galleria" element, if you set style="margin-left: 0" then the carousel is moved, then returned to the -100% position.
So the reason it is happening is because that is what you are explicitly telling it to! Delete the lines from both andareASinistra and andareADestra
rendiContenitoreGalleria.style.marginLeft = '-' + 100 + '%';

Related

Pure javascript carousel bugs

I am trying to build pure javascript slider following the tutorial here with minor customisation.
The problem I had was: if I add more than 7 slides, 7th and onwards won't display correctly. Only dark grey screen is shown instead of the picture I selected.
I tried debugging for hours and still can't figure it out. Hopefully, some experts can shine some light on this problem.
JSFIddle by the author of the code: https://jsfiddle.net/solodev/yokph2nh/
Snippet of code:
function changeSlides(instant) {
if (!instant) {
animating = true;
manageControls();
$slider.addClass("animating");
$('#slide-content').addClass("animating");
$slider.css("top");
$(".slide").removeClass("active");
$(".slide-" + curSlide).addClass("active");
setTimeout(function() {
$slider.removeClass("animating");
$('#slide-content').removeClass("animating");
// Update content
let currentContent = $(".slide-" + curSlide + " .slide__content").html();
$('#slide-content').html(currentContent);
animating = false;
}, animTime);
}
window.clearTimeout(autoSlideTimeout);
$(".slider-pagi__elem").removeClass("active");
$(".slider-pagi__elem-" + curSlide).addClass("active");
$(".slider-tab__elem").removeClass("active");
$(".slider-tab__elem-" + curSlide).addClass("active");
$slider.css("transform", "translate3d(" + -curSlide * 100 + "%,0,0)");
$slideBGs.css("transform", "translate3d(" + curSlide * 50 + "%,0,0)");
diff = 0;
autoSlide();
}
Here is an altered fiddle of the one you posted, with more images.
https://jsfiddle.net/5xhtq4hL/
Seems to work ok.
Maybe you didn't update the css values for left on the
.slide:nthchild() selector?
This code doesn't seem very DRY though. So much copy pasting.

javascript scrollTop doesn't seem to work

I use a technique where I have a table within a div so as to limit the space covered by the table and scroll instead.
Within the table are checkboxes. These checkboxes effect how the table is rendered. When one is clicked, the table is re-rendered within the div. This always causes the scrollbar to go back to the top which is annoying.
So after I render the table in javascript I do a setTimeout call to asynchronously call a function that sets the scrollTop value back to where it was before the re-render.
Here's the code snipit in question:
Note: (ge() == geMaybe() == document.getElementById())
o.renderAndScroll = function() {
var eTestSection = geMaybe(o.id + '-testSection');
var scrollTop = 0;
if (eTestSection) {
scrollTop = eTestSection.scrollTop;
}
o.render();
if (eTestSection) {
setTimeout(
function() {
console.log('Scrolling from ' + ge(o.id).scrollTop + ' to ' + scrollTop);
ge(o.id).scrollTop = scrollTop;
console.log('Scrolled to ' + ge(o.id).scrollTop);
},
1000);
}
}
My console log output is this each time I change a checkbox state:
Scrolling from 0 to 1357
Scrolled to 0
Any other way to make this work? Note that I made the timeout a full second just to make sure the render was moved to the DOM by the time my scroll code is called. I am using chrome mainly but need it to eventually work cross-browser. I don't use jQuery. If I try to catch the onscroll event in the debugger or even log stuff from an onscroll handler, the chrome debugger crashes when the scrollbar is moved with the mouse.
The correct code is:
o.renderAndScroll = function(fForce) {
var scrollTop = 0;
var eTestSection = geMaybe(o.id + '-testSection');
if (eTestSection) {
scrollTop = eTestSection.scrollTop;
}
o.render(fForce);
setTimeout(
function() {
// re-lookup element after being rendered
var eNewTestSection = ge(o.id + '-testSection');
eNewTestSection.scrollTop = scrollTop;
},
1);
};

Javascript animation too fast

I am trying to write a javascript app which sorts dynamically created divs on a webpage, everything works and it sorts it all as it should, however I want it to animate the divs as they change position due to being sorted, I have code to do this but it moves way too fast, the only way I can see the divs move is if I put an alert in the animation code which looks like this :
function moveAnimation(to,from){
mover1.style.backgroundColor = "rgba(255,100,175,0.8)";
mover2.style.backgroundColor = "rgba(255,100,175,0.8)";
mover1.style.top = parseInt(mover1.style.top) + 10 + 'px';
mover2.style.top = parseInt(mover2.style.top) - 10 + 'px';
from = parseInt(mover1.style.top);
if(from != to && from < to)
{
//alert("TO : " + to + " From : " + from); //This makes it pause so that I can see the divs move
animate = setTimeout(moveAnimation(to,from),1000)
}
else
{
//alert("RET");
return;
}
}
And i call it simply like this :
mover1 = document.getElementById(moving1.id);
mover2 = document.getElementById(moving2.id);
var from = parseInt(in1.style.top);
var to = parseInt(in2.style.top);
moveAnimation(to,from);
When the alert is in place I can see them move frame by frame and it's doing exactly what I want, however it all happens in the blink of an eye with the divs suddenly being sorted, I would like to see them slowly move, any ideas on why my code isn't doing that?

Image Rotation using pure Javascript

PLEASE DO NOT RECOMMEND JQUERY - I AM DOING THIS EXERCISE FOR LEARNING PURPOSES.
I have implemented a JavaScript, which rotates images (_elementSlideChange) on a timer, using a set interval of 10 seconds. Also I have added a slide functionality to this, which is 7 milliseconds (_slideImage).
The image rotates automatically every 10 seconds on page load, and I have also provided next and previous buttons, which allow the user to change the images manually.
_elementSlideChange: function () {
var myString;
var myText;
for (var i = 0; i < this._imgArray.length; i++) {
var imageArr = "url(" + this._imgArray[i].src + ")";
var imageBg = this._imageHolder.style.background + "";
if (imageArr == imageBg) {
if (i == (this._imgArray.length - 1)) {
myString = "url(" + this._imgArray[0].src + ")";
myText = this._infoArray[0];
} else {
myString = "url(" + this._imgArray[(i + 1)].src + ")";
myText = this._infoArray[i + 1];
}
}
}
this._imageNextSlide.style.background = myString;
this._imageNextSlide.style.background);
this._infoElement.innerHTML = myText;
this._myTimer = setInterval(MyProject.Utils.createDelegate(this._slideImage, this), 7);
},
_slideImage: function () {
if (parseInt(this._imageHolder.style.width) >= 0 && parseInt(this._imageNextSlide.style.width) <= 450) {
this._imageHolder.style.backgroundPosition = "right";
this._imageHolder.style.width = (parseInt(this._imageHolder.style.width) - 1) + 'px';
console.log(this._imageNextSlide.style.background);
this._imageNextSlide.style.width = (parseInt(this._imageNextSlide.style.width) + 1) + 'px';
} else {
console.log("reached 0px");
if (parseInt(this._imageHolder.style.width) == 0) {
this._imageHolder.style.background = this._imageNextSlide.style.background;
this._imageHolder.style.width = 450 + 'px';
this._imageHolder === this._imageNextSlide;
this._imageHolder.className = "orginalImage";
this._imageNextSlide.style.width = 0 + "px";
this._imageNextSlide = this._dummyImageNextSlide;
this._imagesElement.appendChild(this._imageHolder);
this._imagesElement.appendChild(this._imageNextSlide);
clearInterval(this._myTimer);
}
clearInterval(this._myTimer);
clearInterval(this._elementSlideChange);
}
}
So when the user clicks on the Next arrow button, the event listener for "click" is triggered. This creates a div for the current image on display, and creates a new div, which will contain the next image. The image slide and rotation works correctly (whether it's onLoad or onClick). The issue I have is if I click the Next button, while the new div image is sliding into position, it causes it to run into an infinite loop, so the same div with the image to be displayed keeps sliding in, and the more you click the Next button, the faster the image starts to rotate.
I have tried putting a clear interval for the image rotation and slider, but I do understand my code is wrong, which causes the infinite loop of the sliding image. And I know I am close to finishing the functionality.
Can anyone please advise where I could be going wrong? Or should I try to implement the sliding DIV in another way?
Once again please don't recommend jQuery.
And thank you for your help in advance.
Kush
To solve the issue, I did re-write the entire code, where I had a next and previous button event listener.
myProject.Utils.addHandler(this._nextImageElement, "click", myProject.Utils.createDelegate(this._changeImage, this));
Both the buttons will call the same function :
_changeImage: function (e)
In this function I check to see if the function is Transition (changing images),
I declare a boolean var forward = e.target == this._nextImageElement;
Then check to see the current index if forward ? Add 1 else minus 1
this._currentImageIndex += forward ? 1 : -1;
If its at the end of the Array and forward is true, assign the this._currentImageIndex to reset to 0 or Array.length – 1 if it’s in reverse
Then call another function which gives the ‘div’ a sliding effect. In this case call it this._transitionImage(forward);
In this function, set the this._inTranstion to true. (Because the div’s are sliding in this case).
The following code solved the issue i was having.
this._slideImageElement.style.backgroundImage = "url(\"" + this._imgArray[this._currentImageIndex].src + "\")";
this._slideImageElement.style.backgroundPosition = forward ? "left" : "right";
this._slideImageElement.style.left = forward ? "auto" : "0px";
this._slideImageElement.style.right = forward ? "0px" : "auto";
The above code is very important as the object is to place the “sliding in div” Left or Right of the current Visible “div” to the user, and this is mainly dependent on if the forward variable is true or false.
var i = 0;
Then start the transition by
setInterval( function() {
this._currentImageElement.style.backgroundPosition = (forward ? -1 : 1) * (i + 1) + "px";
this._slideImageElement.style.width = (i + 1) + "px";
Notice the forward will determine if the bgPosition will go to the left if its forward as we multiple by -1 or +1,
So for example
If the user clicks NEXT BUTTON,
Forward = true
So the first thing we do is set the
this._slideImageElement.style.backgroundPosition = "left"
Then
this._slideImageElement.style.left = "auto"
this._slideImageElement.style.right = "0px"
This means when the sliding image moves in its background position is LEFT but the div is placed on the RIGHT to 0px;
then this._currentImageElement.style.backgroundPosition = -1 * (i + 1)
Which moves the position of the currentImageElement to the left by 1px,
Increase the width of the slideImage which in this case is right of the current div,
and as the current div moves to the left the sliding image starts to appear from the right. (By default set the width of slideImageElement to 0px so the div exists but isn’t visible to the user). This gives it the slide effect of moving forward new image coming from the right.
this._slideImageElement.style.width = (i + 1) + "px";
then declare it to stop when it it’s the image width. In this case it will be 500px.
if ((i = i + 2) == 500) {
In this if statement reset the currentImageElement background and the background position “right” or “left” don’t really matter as long it has been reset.
Clear the interval
Set the transition to false again
Then call a setTimeout for the function changeImage, which will continue until the slide is completed.
The following shows the reset code as this is very important to prevent repeating the same image (This solved my entire issue)
// set the current image to the "new" current image and reset it's background position
this._currentImageElement.style.backgroundImage = "url(\"" + this._imgArray[this._currentImageIndex].src + "\")";
this._currentImageElement.style.backgroundPosition = "right";
// reset the slide image width
this._slideImageElement.style.width = "0px";
// clear the transition interval and mark as not in transition
clearInterval(this._transitionInterval);
this._inTransition = false;
// setup the next image timer
this._nextImageTimeout = setTimeout(myProject.Utils.createDelegate(this._changeImage, this), 2500);
}
I have provided a thorough detail because then it easier to understand the logic of the problem, and even if your not having the same issue, this may help you fingure out any problem.
I couldn't provide a JSfiddle, as i have created my CSS using Javascript, there are different ways of doing this, but i wanted to understand the logic behind the forward and reverse, and having a timer which continuously goes forward.
It seems like you want to cancel the animation on the slide (perhaps have it fade out while the next slide animates in, cancel its animation abruptly or let it finish and ignore the button click)
What I usually do, personally, is check for the animated state (yes, I use jquery, but you should be able to test the CSS or positioning values you are using to animate in the same way) you could even add an "active" class or data type during animation to make testing easier. Global flags work, too. If there is animation, ignore the button. (For my work... Depends on your intention)
Like I said, the problem may be with button behaviour not with the animation routine. It would be useful to see how you are calling this from the button click, and what your intended results are going to be.
How about CSS3 transitions?
transition: all 1s ease 0.5s;
Simple example on JS Fiddle.
This takes care of the animation, so you just need to set the intended destination using JavaScript, i.e.
this.style.left = '100px';
Or
this.style.top = '30px';
And CSS3 transitions will smoothly slide the element.
Cross Browser Note!
The transition property may need a vendor prefix for some browsers, I am using the latest production Firefox and you don't need -moz for that. Same goes for Opera, no '-o' required. Internet Exporer 10 needs no prefix. You may need to use -webkit for Safari / Chrome, but test without first.

How to slide images in from the side using JavaScript?

I have a script that displays images sort of like a carousel. The images are placed in LIs and the left positioning is changed based on the width of each slide (all the same). Currently, the old slide just disappears then the new one appears.
I would like to make it so they slide in from the side and was wondering if someone could give me a basic example of how to do this using plain JavaScript (no jQuery!).
For example, I'm using the following code to update the left positioning of the containing UL. How can I make it so it will slide the selected image to the left or to the right (depending upon whether the next or previous button is clicked)
containingUL.style.left = '-' + (slideNumber * slideWidth) + 'px';
Here's a basic element slide function. You can play with the values of steps and timer to get the animation speed and smoothness just right.
function slideTo(el, left) {
var steps = 25;
var timer = 25;
var elLeft = parseInt(el.style.left) || 0;
var diff = left - elLeft;
var stepSize = diff / steps;
console.log(stepSize, ", ", steps);
function step() {
elLeft += stepSize;
el.style.left = elLeft + "px";
if (--steps) {
setTimeout(step, timer);
}
}
step();
}
So you could go:
slideTo(containingUL, -slideNumber * slideWidth);
Edit: Forgot to link to the JSFiddle
Edit: To slide to the left, provide a left value less than the current style.left. To slide to the right, provide a value greater than the current style.left. For you it shouldn't matter much. You should be able to plug it into your existing code. I'm guessing your current code either increments or decrements slideNumber and then sets style.left according to the slideNumber. Something like this should work:
if (nextButtonClicked) slideNumber++;
else slideNumber--;
slideTo(containingUL, -slideNumber * slideWidth);
I updated the JSFiddle with a working example of a sliding "gallery", including prev and next buttons. http://jsfiddle.net/gilly3/EuzAK/2/
Simple, non jQuery:
http://sandbox.scriptiny.com/contentslider/slider.html
http://www.webmonkey.com/2010/02/make_a_javascript_slideshow/
http://javascript.internet.com/miscellaneous/basic-slideshow.html

Categories

Resources