Event AFTER scroll event stops? - javascript

So I have a box shadow that i want to add to a bar as shown in this example :
https://jsfiddle.net/eddietal2/qgLvsx2v/
this is the javascript that I have:
var topBar = document.getElementById('top-bar');
var wrapper = document.getElementById('wrapper');
wrapper.onscroll = function () {
topBar.style.boxShadow = "10px 20px 30px blue"
}
The effect I am going for is, when the user scrolls, I want the box shadow to appear, but when they stop scrolling, I want the box shadow to disappear. How can I achieve this effect?

You could use a timer to check if you have scrolled in the last N ms and call a callback after that about of time.
var wrapper = document.getElementById('wrapper')
function onScroll(element, scrolling, stopped) {
let timer = null
// bind the event to the provided element
element.addEventListener('scroll', function (e) {
// use a class to switch the box-shadow on
element.classList.add('scrolling')
if (typeof scrolling === 'function') {
scrolling.apply(this, arguments)
}
// clear the existing timer
clearTimeout(timer)
// set a timer for 100 ms
timer = setTimeout(() => {
// if we get in here the page has not been scrolled for 100ms
// remove the scrolling class
element.classList.remove('scrolling')
if (typeof scrolling === 'function') {
stopped.apply(this, arguments)
}
}, 100)
})
}
// call the function
onScroll(wrapper,
function scrolling(e) {
e.target.classList.add('scrolling')
},
function stopped(e) {
e.target.classList.remove('scrolling')
}
)
* {
box-sizing: border-box;
}
#wrapper {
height: 200px;
padding: 2em;
overflow: auto;
transition: .4s box-shadow;
}
#wrapper.scrolling {
box-shadow: 0px 0px 60px blue inset;
}
#topBar > div {
background: #eee;
height: 200px;
width: 200px;
margin-bottom: 1em;
position: relative;
transition: .4s all;
}
#wrapper.scrolling #topBar > div {
transform: perspective(1200px) translateZ(20px);
box-shadow: 2px 2px 10px #777;
}
<div id="wrapper" class="">
<div class="" id="topBar">
<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
</div>
</div>

There is not 'scrollstop' event. You need to identify when the user stops scrolling yourself.
When the user scrolls, start a timer for a few dozen milliseconds (you'll have to play with this value), and clear any existing timers. When the timer reaches 0, call your function.

Onscroll is easy to monitor to apply the shadow but removing the shadow is the tricky part and the best I could think of was the event mouseout...
<!DOCTYPE html>
<html>
<head>
<style>
div {
border: 1px solid black;
width: 200px;
height: 100px;
overflow: scroll;
}
</style>
</head>
<body>
<div onmouseout="this.style.boxShadow='none';" onscroll="this.style.boxShadow='10px 20px 30px blue';">In my younger and more vulnerable years my father gave me some advice that I've been turning over in my mind ever since.<br><br>
'Whenever you feel like criticizing anyone,' he told me, just remember that all the people in this world haven't had the advantages that you've had.'</div>
</body>
</html>

Related

How do I hide a scrollbar after scrolling and make it visible again on scroll?

My intention is to hide my scrollbar (i.e, hidden by SLIDING TO THE RIGHT), after scrolling (let's say, like 2 or 3 seconds after I'm done scrolling)
And to make it visible again, soon as I start scrolling (i.e, visible by SLIDING IN FROM THE RIGHT)
VIEW CODE SNIPPET:
div::-webkit-scrollbar {
width: 8px;
/* helps remove scrollbar which resizes or shifts list items */
/* display: none; */
}
div::-webkit-scrollbar-track {
background-color: #444444;
}
div::-webkit-scrollbar-button:vertical:increment {
background-color: rgba(108, 92, 231, 0.65);
}
div::-webkit-scrollbar-button:vertical:decrement {
background-color: rgba(108, 92, 231, 0.65);
}
div::-webkit-scrollbar-thumb {
background-color: rgba(108, 92, 231, 0.7);
border-radius: 10px;
}
div::-webkit-scrollbar-thumb:hover {
background-color: rgba(108, 92, 231, 1);
}
div {
width: 500px;
height: 300px;
background-color: #ececec;
overflow: auto;
}
<div>
<p style="height: 300vh;">Just some tall paragraph to force DIV scrollbars....</p>
</div>
Please help me everyone (I'D BE SO GRATEFUL!)
:D
Since CSS does not have timeouts and clearing of timeouts - Use JavaScript
Use Element.classList to add and remove a class
Use setTimeout() set at 2500ms, but every time a scroll event is triggered remove the previous pending timeout using clearTimeout. Logically, after you finished scrolling the last timeout that was set will, after 2.5s trigger finally the class removal.
Use a CSS class like .is-scrolling to there define the desired scrollbar styles (which otherwise are transparent by default)
const showScrollbars = (evt) => {
const el = evt.currentTarget;
clearTimeout(el._scrolling); // Cancel pending class removal
el.classList.add("is-scrolling"); // Add class
el._scrolling = setTimeout(() => { // remove the scrolling class after 2500ms
el.classList.remove("is-scrolling");
}, 2500);
};
document.querySelectorAll("[data-scrollbars]").forEach(el => {
el.addEventListener("scroll", showScrollbars);
});
[data-scrollbars] {
width: 500px;
height: 180px;
background-color: #ececec;
overflow: auto;
}
[data-scrollbars]::-webkit-scrollbar {
width: 8px;
height: 8px;
}
[data-scrollbars]::-webkit-scrollbar-track {
background-color: transparent;
}
[data-scrollbars]::-webkit-scrollbar-thumb {
background-color: transparent;
border-radius: 10px;
}
[data-scrollbars].is-scrolling::-webkit-scrollbar-track {
background-color: #777;
}
[data-scrollbars].is-scrolling::-webkit-scrollbar-thumb {
background-color: gold;
}
<div data-scrollbars>
<p style="height: 300vh;">
Just some tall paragraph to force DIV scrollbars...<br>
Scroll me! (<<< PS: See the problem?!)
</p>
</div>
I would highly not advise you hide scrollbars. Scrollbars are a visual hint to the user that there's actually content to be scrolled. Do a simple A/B testing. For half of your visitors show the scrollbar. For the other half, do that funky stuff - and don't be surprised that your click trough-rate for the below-the-fold portion of the app (or element) has fewer-to-none interactions by that second group of users.
I am thinking about what if user do not have any mouse wheel for scrolling and if user scroll with the actually using scroll bar.
Anyway please search for slim fading scroll bar example at google. You will find some examples for the slim scroll maybe it’s not invisible but it’s transparent and have a good shape.

Why do my css animations become exponentially smaller and eventually stop working?

I am making a small game where a block slides towards the character, and onclick of the main body of the game through a mouse, the character jumps to avoid the block. Whenever I refresh the page, it works normally, but after a few clicks the animation gets smaller and smaller (in the distance is jumps and the time it takes for the animation to complete) and eventually stops working completely. I have included a code snippet so you can see the problem.
let character = document.getElementById('character');
let obstacle = document.getElementById('obstacle');
function jump() {
if (character.classList != 'animate') {
character.classList.add('animate');
}
setInterval(function () {
character.classList.remove('animate');
}, 500);
}
* {
padding: 0;
margin: 0;
}
.game {
height: 200px;
width: 500px;
border: 5px solid black;
}
#keyframes jump{
0%{top: 150px;}
30%{top: 100px;}
70%{top: 100px;}
100%{top: 150;}
}
.character {
height: 50px;
width: 20px;
background-color: red;
position: relative;
top: 150px;
}
.animate {
animation: jump 0.5s;
}
#keyframes block{
0%{left: 480px;}
100%{left: -40px;}
}
.obstacle {
height: 20px;
width: 20px;
background-color: blue;
position: relative;
top: 130px;
left: 480px;
animation: block 2s infinite linear;
}
<!DOCTYPE html>
<html>
<head>
<title>Jumping Game</title>
<link rel="stylesheet" href="jump.css">
</head>
<div>
<body onclick="jump()">
<div class="game">
<div id="character" class="character">
</div>
<div id="obstacle" class="obstacle">
</div>
</div>
</body>
</div>
<script src="jump.js"></script>
</html>
Because you use setInterval, which executes the function provided to it repeatedly in 500ms intervals until you stop it with clearInterval (passing timeout id returned from initial setInterval call).
If you only want to execute the function once after 500ms, use setTimeout instead: https://jsfiddle.net/dp0n8Leh/ (making sure you first clearTimeout for the previous timeout, if you click early enough)
Also, to check if an element has a class, you should use !character.classList.contains('animate') instead of character.classList != 'animate'
just use setTimeout not setInterval to remove the class

How can I restart a CSS transition as soon as it ends using standard JavaScript?

I have built a kind of password generator that should display a new password whenever the countdown expires. Unfortunately, I have only managed to figure out how to run my code once. The countdown consists of a simple CSS transition, which I would like to keep, because it is much smoother than my other attempts, wherein i tried to repeatedly update the width using JavaScript.
var dictionary = {
"adverbs": [
"always",
"usually",
"probably"
],
"adjectives": [
"useful",
"popular",
"accurate"
],
"nouns": [
"computer",
"software",
"terminal"
]
};
function capitalizeFirst(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
function randomIndex(object) {
return object[Math.floor(Math.random() * object.length)];
}
function generatePassword() {
var category = ["adverbs", "adjectives", "nouns"];
var password = [];
for (i = 0; i < category.length; i++) {
password.push(capitalizeFirst(randomIndex(dictionary[category[i]])));
}
password.push(Math.floor(Math.random() * 8999) + 1000);
return password.join("");
}
function updatePassword() {
document.getElementById("countdown-fill").style.width = 100 + '%';
document.getElementById("text-field").value = generatePassword();
document.getElementById("countdown-fill").style.width = 0 + '%';
}
setInterval(updatePassword, 5000);
#import url('https://fonts.googleapis.com/css?family=Nunito&display=swap');
body {
margin: 0;
width: 100%;
height: 100%;
background-color: #f8f8f8;
}
.container {
max-width: 400px;
margin: 0 auto;
}
#text-field {
font-size: 15px;
font-weight: 400;
font-family: 'Nunito', sans-serif;
margin-top: 100px;
margin-bottom: 10px;
width: 100%;
height: 30px;
padding: 10px;
box-sizing: border-box;
border: 1px solid #e5e5e5;
background-color: #ffffff;
}
#countdown-background {
width: 100%;
height: 10px;
box-sizing: border-box;
border: 1px solid #e5e5e5;
background-color: #ffffff;
}
#countdown-fill {
width: 100%;
height: 100%;
transition: width 5s;
transition-timing-function: linear;
background-color: #1e87f0;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Password Generator</title>
</head>
<body>
<div class="container">
<input id="text-field" type="text" spellcheck="false">
<div id="countdown-background">
<div id="countdown-fill"></div>
</div>
</div>
</body>
</html>
Currently, I have two apparent issues with my code:
The transition becomes delayed due to setInterval. This is not the case if I simply call updatePassword on its own.
The CSS transition only animates once. I would like to reset the animation every time i call updatePassword.
I came across a few jQuery solutions for my problem, but I am not very interested in those, as I want to rely on standard JavaScript as much as possible. However, I am okay with alternative CSS tools like keyframes, which seem to work well:
#countdown-fill {
width: 100%;
height: 100%;
animation: refresh 5s infinite;
background-color: #1e87f0;
}
#keyframes refresh {
from {
width: 100%;
}
to {
width: 0;
}
}
Although, I do worry about synchronization issues as the animation is not coupled with updatePassword in any way.
Question: Is there a way to have updatePassword reset the animation each time I call the function, and remove the initial delay?
JSFiddle: https://jsfiddle.net/MajesticPixel/fxkng013/
I've modified your JSFiddle, here's the explanation.
#countdown-fill {
width: 100%;
height: 100%;
transform-origin: left;
background-color: #1e87f0;
}
.reset {
transition: transform 5s linear;
transform: scaleX(0);
}
The trick is to bind the transition to a class, and when you want to reset it you just remove the class (reset the transition to the initial status) and add it again (restart it).
But there are a few gotchas: the most important is that instantly removing and adding the class will be optimized by the browser, which will just merge the actions and no transition at all will happen. The trick is to wrap the calls in a nested rAF call, which will force the browser to execute, render, and then execute again.
window.requestAnimationFrame(function() {
document.getElementById("countdown-fill").classList.remove('reset');
window.requestAnimationFrame(function() {
document.getElementById("countdown-fill").classList.add('reset');
});
});
The second is related to transitions: to optimize browser rendering, avoid transitioning properties like width or height, and try to limit to transforms and opacity. I've changed your width transition into a transform transition: same effect, more performance.
I second what NevNein has posted, and would also like to add that if you want to couple the transition with updatePassword so that they have a linked relationship and not just matched timeouts, you should replace setInterval(updatePassword, 5000) with:
updatePassword();
document.getElementById('countdown-fill').addEventListener("transitionend", updatePassword)
The countdown and password change will now run at any speed you set in the CSS.

Why does my jquery take so long when animating on scroll?

I have a box that slides right 100px when you scroll 10px and slide back to it's default location if the scroll is less than 10px. The box does animate, however, there is a bit of a delay when it does. Can anyone help me figure this out?
HTML
<div id="nest">
<div id="box">
</div>
</div>
CSS
#nest {
width: 95%;
max-width: 1000px;
margin: auto;
background-color: orange;
height: 1000px;
padding-top: 150px
}
#box {
margin: 50px 0px 0px 0px;
width: 100px;
height: 100px;
position:relative;
background-color: green;
}
jQuery
jQuery(window).scroll(function() {
if (jQuery(this).scrollTop() > 10) {
jQuery('#box').animate({left:'100px'})
} else {
jQuery('#box').animate({left:'0px'})
}
});
My JSFIDDLE LINK
https://jsfiddle.net/ispykenny/m6ffj83g/1/
thanks in advance for your time and help!
The reason your animation is taking so long would be that the animate is running on every scroll event past 10px, and this is quite intensive on the client-side. There are a few options, either experiment with the .stop() functionality in jQuery, or write a a conditional if statement that checks if the animation will have started and only fires if it hasn't.
https://api.jquery.com/stop/
this is a handy resource.
var coin = false;
jQuery(window).scroll(function() {
if (jQuery(this).scrollTop() > 10 && coin === false) {
jQuery('#box').animate({left:'100px'});
coin = true;
} else if (coin === true && jQuery(this).scrollTop() <= 10) {
jQuery('#box').animate({left:'0px'});
coin = false;
}
});
try this!

List rotation with limited elements

I have div container with list (cards) inside. When I hover it, cards start to moving (translateX animation). container's width is 300px, elements count in container:3, each element width:100px.
So you can see 3 elements in container together overflow:hidden. What I want to make?, is that when there is no element to show translateX animation -100px = 100px blank space after third element, it start from 1 elements in the list immediately after last, with no blank space.
For now, I have no idea how it could be done without duplicates and etc.
Here is what I have at the moment:
Fiddle (Hover cards to see translation animation)
UPD 1:
The code and data (cards count, container size) was taken for example, i'll try to explain better what i want: My goal is to built list of cards and after button was pressed, the list will start moving (like in example with translateX animation) for some time (for example translateX: 12491px, animation-duration: 15s;) and stops. But problem is that amount of crads in the list would be in range of 3-40 cards (each card is 100px width & height). So, when i'll set translateX: 12491px for example, it will be out of range and after the last card in the list would appear blank space. I want first and last card to be tied somehow and after the last card immediately appears first card in the list and etc.. Maybe i am searching for solution in a wrong way, but i guess you understand the main idea.
UPD 2:
I found that cs:go uses animation that i wanted to write on html\css\js. Here is video: youtube.com
html:
<div class="container">
<div class="cards">
<div class="card">
1
</div>
<div class="card">
2
</div>
<div class="card">
3
</div>
</div>
</div>
css:
.container
{
width:300px;
height: 100px;
border: 2px solid black;
overflow: hidden;
}
.card
{
float:left;
height: 100px;
width: 100px;
background-color:blue;
box-sizing: border-box;
border: 2px solid red;
color: white;
font-size: 23px;
}
.cards:hover
{
transform: translateX(-100px);
transition-duration: 3s;
animation-duration: 3s;
animation-fill-mode: forwards;
}
start from 1 elements in the list immediately after last, with no
blank space
This is beyond CSS and you will need Javascript for that. Because, you have tagged the question with Javascript and not jQuery, my answer would be limited to pure Javascript only. Look ma, no JQuery ;)
I have no idea how it could be done without duplicates
Here is a DIY (do it yourself) idea..
The main trick is to show at least one item less than the total you have. If you have 3 cards, show only 2. If you have 4 cards, show only 3. Why, because you need to re-position a card when it goes out of view and wrap it back at the end. If you show exactly the same number of cards that you have, then you cannot break half-a-card and wrap it and you will see some blank space until the first one goes out of view. You get the idea?
Do not use translate or you will end up complicating things for yourself while scripting it out. Keep things simple.
Do not use a wrapper for your cards. Why? Because, we will be re-positioning the cards which have gone out of view. When we do that, the next card will take up its place and immediately go out of view making things further difficult for you.
To keep things simple, arrange your cards with absolute positioning relative to its container. To start with, let all cards stack up at top:0; and left: 0;.
Next wire-up Javascript to position the left property based on the width of each card and arrange them linearly.
Use requestAnimationFrame to control the animation.
Keep track of the left-most card and its left position. When this goes out of view (which is 0 minus width), appendChild this card to its container. This will move the card to the end of cards. Also, change the left property to it based on the last card in the list.
That' all there is to it.
Below is a demo. To make it easy for you to experiment, I have used a settings object to keep the configurable properties which you can easily tweak and see. Look closely at the code and you will find it simple to understand. You can set the iterations settings to 0 to make the animation infinite.
Also, note that you do not need to duplicate or fake the cards. Try the demo and add as many cards you want to.
The inline code comments in the snippet, will further help you understand each line of code and relate to the steps above.
Snippet:
var list = document.querySelector('.cardList'), // cache the container
cards = document.querySelectorAll('.card'), // cache the list of cards
start = document.getElementById('start'), // buttons
stop = document.getElementById('stop'),
reset = document.getElementById('reset'),
raf, init = 0, counter = 0, lastCard, currentIteration = 0, // general purpose variables
settings = { // settings object to help make things configurable
'width': 100, 'height': 100, 'speed': 2,
'iterations': 2, 'count': cards.length
}
;
start.addEventListener('click', startClick); // wire up click event on buttons
stop.addEventListener('click', stopClick);
reset.addEventListener('click', resetClick);
initialize(); // initialize to arrange the cards at start
function initialize() {
// loop thru all cards and set the left property as per width and index position
[].forEach.call(cards, function(elem, idx) {
elem.style.left = (settings.width * idx) + 'px';
});
init = -(settings.width); // initialize the view cutoff
lastCard = cards[settings.count - 1]; // identify the last card
counter = 0; currentIteration = 0; // reset some counters
settings.speed = +(document.getElementById('speed').value);
settings.iterations = +(document.getElementById('iter').value);
}
function startClick() {
initialize(); raf = window.requestAnimationFrame(keyframes); // start animating
}
function stopClick() { window.cancelAnimationFrame(raf); } // stop animating
function resetClick() { // stop animating and re-initialize cards to start again
window.cancelAnimationFrame(raf);
document.getElementById('speed').value = '2';
document.getElementById('iter').value = '2';
initialize();
}
// actual animation function
function keyframes() {
var currentCard, currentLeft = 0, newLeft = 0;
// iterate all cards and decrease the left property based on speed
[].forEach.call(cards, function(elem, idx) {
elem.style.left = (parseInt(elem.style.left) - settings.speed) + 'px';
});
currentCard = cards[counter]; // identify left-most card
currentLeft = parseInt(currentCard.style.left); // get its left position
if (currentLeft <= init) { // check if it has gone out of view
// calculate position of last card
newLeft = parseInt(lastCard.style.left) + settings.width;
list.appendChild(currentCard); // move the card to end of list
currentCard.style.left = newLeft + 'px'; // change left position based on last card
lastCard = currentCard; // set this as the last card for next iteration
counter = (counter + 1) % settings.count; // set the next card index
if ((settings.iterations > 0) && (counter >= (settings.count - 1))) {
currentIteration++; // check settings for repeat iterations
}
}
if (currentIteration >= settings.iterations) { return; } // when to stop
raf = window.requestAnimationFrame(keyframes); // request another animation frame
};
* { box-sizing: border-box; padding: 0; margin: 0; }
.cardList {
position: relative; height: 100px; width: 300px;
margin: 10px; border: 2px solid #33e;
overflow: hidden; white-space: nowrap;
}
.card {
position: absolute; left: 0; top: 0; text-align: center;
height: 100px; width: 100px; line-height: 100px;
background-color: #99e;
font-family: monospace; font-size: 2em; color: #444;
border-left: 1px solid #33e; border-right: 1px solid #33e;
}
div.controls, button { margin: 10px; padding: 8px; font-family: monospace; }
div.controls input { width: 48px; padding: 2px; text-align: center; font-family: monospace; }
<div class="controls">
<label>Speed <input id="speed" type="number" min="1" max="8" value="2" />x</label>
|
<label>Iterations <input id="iter" type="number" min="0" max="8" value="2" /></label>
</div>
<div class="cardList">
<div class="card">1</div>
<div class="card">2</div>
<div class="card">3</div>
<div class="card">4</div>
</div>
<button id="start">Start</button>
<button id="stop">Stop</button>
<button id="reset">Reset</button>
Fiddle: http://jsfiddle.net/abhitalks/1hkw1v0w/
Note: I have left out a few things in the demo. Especially, although width and height of the cards is part of the settings object, but currently it left fixed. You can easily use the settings object to make the dimensions of the cards configurable as well.
Edit:
(as per Op's comment)
If you want a greater control over distance to scroll, duration and timing-functions (easing), then you could implement those yourself using a library. A couple of such good libraries are the Robert Penner's Easing Functions and a jQuery plugin from GSGD. Although you can implement all of that with pure Javascript, it would be easier if you use a library like jQuery.
Catch here is that in order to do so effectively, you must then duplicate the cards. You can do so easily by cloning the entire list a couple of times.
Although you have not tagged this question with jQuery, here is a small demo (using jQuery to get it done quickly) where you can configure the speed and the distance.
Snippet 2:
var $cardList = $('.cardList').first(),
$cards = $('.card'),
$speed = $('input[name=speed]'),
width = 100,
randomize = true,
distance = 20 * width
;
for (var i = 0; i < 50; i++) {
$cards.clone().appendTo($cardList);
}
function spin() {
var newMargin = 0, newDistance = distance,
speed = +($speed.filter(':checked').val());
if (randomize) {
newDistance = Math.floor(Math.random() * $cards.length * 5);
newDistance += $cards.length * 5;
newDistance *= width;
}
newMargin = -(newDistance);
$cards.first().animate({
marginLeft: newMargin
}, speed);
}
$('#spin').click(function() {
$cards.first().css('margin-left', 0);
spin();
return false;
});
* { box-sizing: border-box; padding: 0; margin: 0; }
.cardList {
height: 100px; width: 302px; position: relative;
margin: 10px; border: 1px solid #33e;
overflow: hidden; white-space: nowrap;
}
.card {
display: inline-block; text-align: center;
height: 100px; width: 100px; line-height: 100px;
background-color: #99e;
font-family: monospace; font-size: 2em; color: #444;
border-left: 1px solid #33e; border-right: 1px solid #33e;
}
.cardList::before, .cardList::after {
content: ''; display: block; z-index: 100;
width: 0px; height: 0px; transform: translateX(-50%);
border-left: 8px solid transparent;
border-right: 8px solid transparent;
}
.cardList::before {
position: absolute; top: 0px; left: 50%;
border-top: 12px solid #33e;
}
.cardList::after {
position: absolute; bottom: 0px; left: 50%;
border-bottom: 12px solid #33e;
}
div.controls, button { margin: 10px; padding: 8px; font-family: monospace; }
div.controls input { width: 48px; padding: 2px; text-align: center; font-family: monospace; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="controls">
<label>Speed: </label>
|
<label><input name="speed" type="radio" value='6000' />Slow</label>
<label><input name="speed" type="radio" value='5000' checked />Medium</label>
<label><input name="speed" type="radio" value='3000' />Fast</label>
</div>
<div class="cardList"><!--
--><div class="card">1</div><!--
--><div class="card">2</div><!--
--><div class="card">3</div><!--
--><div class="card">4</div><!--
--></div>
<button id="spin">Spin</button>
Fiddle 2: http://jsfiddle.net/abhitalks/c50upco5/
If you don't want to modify the dom elements you could take advantage of flex-item's order property;
to do this you'd still need a little JS to add this property after animation has ended;
I also changed to animation instead of transition so it automatically resets the transform property at the end of animation.
$('.cards').mouseenter(function() {
setTimeout(function() {
$('.card').first().css("order", "2");
}, 3000);
});
$('.cards').mouseleave(function() {
$('.card').first().css("order", "-1");
});
.container {
width: 300px;
height: 100px;
border: 2px solid black;
overflow: hidden;
}
.card {
float: left;
/* height: 100px;
width: 100px;*/
background-color: blue;
box-sizing: border-box;
border: 2px solid red;
color: white;
font-size: 23px;
flex: 0 0 25%;
}
.cards:hover {
animation: trans 3s;
}
/**/
.cards {
width: 400px;
height: 100%;
display: flex;
transition: transform 3s;
}
#keyframes trans {
0% {
transform: translateX(0)
}
100% {
transform: translateX(-100px)
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="container">
<div class="cards">
<div class="card">1</div>
<div class="card">2</div>
<div class="card">3</div>
</div>
</div>
fiddle
But if you're OK to use JS I suggest you manipulate the order of DOM elements directly,taking the first child element of .cards and appending it to the end of list at the end of each animation;
try this:
var anim;
$('.cards').mouseenter(function(){
anim = setInterval(function(){
$('.cards').append($('.card').first())
},3000)
});
$('.cards').mouseleave(function(){
clearInterval(anim)
});
.container{
width:300px;
height: 100px;
border: 2px solid black;
overflow: hidden;
}
.card{
float:left;
/* height: 100px;
width: 100px;*/
background-color:blue;
box-sizing: border-box;
border: 2px solid red;
color: white;
font-size: 23px;
/**/
flex:0 0 25%;
}
.cards:hover{
animation: trans 3s infinite;
}
/**/
.cards{
width:400px;
height:100%;
display:flex;
}
#keyframes trans {
0% {
transform: translateX(0)
}
100% {
transform: translateX(-100px)
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="container">
<div class="cards">
<div class="card">
1
</div>
<div class="card">
2
</div>
<div class="card">
3
</div>
</div>
</div>
in case you want one card to be present at same time both at the beginning and at the end of card-list you'll need to make a deep-copy / clone of the element;
here's an example;
Update 2:
I wrote a jquery plugin that may act the way you want:
you can add as many cards as you want, right now the "translateX" is random (the script will choose randomly the final card)
link to the demo
Update:
I know, I used duplicates, but now my code works on three cards:
I added three "fake" cards
Each "real" card has it's own animation
the "fake" cards will be overlapped by the real ones once their cycle is finished ("when there is no element to show" as you asked)
check the snippet:
.container {
width: 300px;
height: 100px;
border: 2px solid black;
overflow: hidden;
}
.card {
float: left;
height: 100px;
width: 100px;
background-color: blue;
box-sizing: border-box;
border: 2px solid red;
color: white;
font-size: 23px;
}
.cards {
width: 600px;
}
.container:hover .card1{
animation: 1600ms slide1 infinite linear;
}
.container:hover .card2{
animation: 1600ms slide2 infinite linear;
}
.container:hover .card3{
animation: 1600ms slide3 infinite linear;
}
.fakecard{z-index:-1000;}
.container:hover .fakecard{
animation: 1600ms fakeslide infinite linear;
}
#keyframes slide1 {
0% { transform: translateX(0px); }
33% { transform: translateX(-100px); }
33.1% { transform: translateX(+200px); }
100% { transform: translateX(0px); }
}
#keyframes slide2 {
0% { transform: translateX(0px); }
66% { transform: translateX(-200px); }
66.1% { transform: translateX(100px); }
100% { transform: translateX(0px); }
}
#keyframes slide3 {
0% { transform: translateX(0px); }
99% { transform: translateX(-300px); }
99.1% { transform: translateX(+300px); }
100% { transform: translateX(0px); }
}
#keyframes fakeslide {
0% { transform: translateX(0px); }
99% { transform: translateX(-300px); }
99.1% { transform: translateX(+300px); }
100% { transform: translateX(0px); }
}
<div class="container">
<div class="cards">
<div class="card card1">
1
</div>
<div class="card card2">
2
</div>
<div class="card card3">
3
</div>
<div class="card fakecard">
1 (fake)
</div>
<div class="card fakecard">
2 (fake)
</div>
<div class="card fakecard">
3 (fake)
</div>
</div>
</div>
Previous answer:
Is this what you are trying to achieve?
I don't think you can do it without duplicates...
If not, can you explain better what you are trying to achieve here?
[snipped code removed]
Here is the same effect that you mentioned, with a little tweak on your CSS and a helpful hand from jQuery.
CSS
Change your selector for the translateX animation to apply on each of the .card boxes when their immediate parent is hovered, and not the .cards (which is the immediate parent of the .cards). This is because you'd want the cards to move to the left, and not the window through which they appear while making the movement.
That is,
.cards:hover .card {
transform: translateX(-100px);
transition-duration: 1.5s;
animation-duration: 1.5s;
animation-fill-mode: forwards;
}
jQuery
var $container = $('.container');
var cardWidth = 100;
$container.on('mouseenter', function (e) {
e.preventDefault();
var $card0Clone = $('.card').eq(0).clone(); // clone of the first .card element
$('.cards').append($card0Clone);
updateWidth();
});
$container.on('mouseleave', function (e) {
e.preventDefault();
var $cards = $('.card');
$cards.eq(0).remove(); // remove the last .card element
});
function updateWidth() {
$('.cards').width(($('.card').length) * cardWidth); // no of cards in the queue times the width of each card would result in a container fit enough for all of them
}
Code Explained
As you move in the mouse pointer, a clone of the first card is created, and appended to the end of the cards collection. Further, as you move the mouse out of the hover area, the original .card (which was cloned earlier) will be removed from the head of the queue - hence, producing a cyclic effect.
The real trick though is with the updateWidth function. Every time the mouse enters the .container the width of the .cards' immediate parent (i.e. .cards div) is updated, so that .cards div is wide enough to fit in all the .cards, and therefore, making sure that each of the cards push against each other and stay in one line at the time the translation animation is being done.
Here is a simple technique that manipulates the Dom to create your desired effect
Javascript:
document.querySelector('.cards').addEventListener('mousedown', function(e) {
if (e.clientX < (this.offsetWidth >> 1)) {
this.appendChild(this.removeChild(this.firstElementChild));
} else {
this.insertBefore(this.lastElementChild, this.firstElementChild);
}});
then in you css use the nth-of-type selector to position elements as required.
Here is your fiddle
If you are using mouseover you might need to wait for transitionend event before firing again.
Check out this demo
Here I used JQuery, you can configure your animation using two variables
var translateX = 1000; //adjust the whole distance to translate
var stepSpeed = 100; //adjust the speed of each step transition in milliseconds
After setting your variables, on the click event of the cards do the following:-
Get the number of the steps required based on translateX
Loop for the number of steps
Inside each loop (each step) move the cards 1 step to the left, then put the first card to the end of the cards to form the connected loop, then return back the cards to it's initial position
Here is the code:
var stepsNumber = translateX/100;
for(var i=0; i< stepsNumber; i++)
{
$('.cards').animate({'left' : -100}, stepSpeed,function(){
$('.cards div:last').after($('.cards div:first'));
$('.cards').css({'left' : '0px'});
});
}

Categories