how to make a flip animation horizontal with CSS and Javascript - javascript

i made a blackjack game , i want to make the dealer cards flip from back to front everything works expect that when the shown cards appear they apper one under another .. how can i make them appear
in line ??
function TurnDealerCards()
{
DealerCards.innerHTML = "";
for (var i = 0; i < DealerArray.length; i++) {
var Dealercard = document.createElement('img');
var random = Math.floor((Math.random() * 10));
Dealercard.setAttribute("width", 50);
Dealercard.setAttribute("src", (allCards[random])[(DealerArray[i])]);
DealerCards.appendChild(Dealercard);
}
DealerCards.className = 'myDIV';
}
.myDIV {
display:inline-block;
border: 0px;
width: 50px;
background-color:transparent;
color: transparent;
animation: mymove 1s ;
}
#keyframes mymove {
50% {
transform: rotateY(180deg);
}
}
<table border="0" width="100%" height="100%" style="text-align: center">
<tr><th id="NewGame" onclick="MakeAnewGame();" style="float:left">
<img src="media/cards/new game.png" width="100" /><label>change table color</label><input id="changeBGC" type="button" onclick="changeBackground();">
</th></tr>
<tr><td style="height:100pt;width:100%;font-size:100pt;color:white"><div id="dealer"></div></td></tr>

Use display:flex to the wrap (myDiv) and use animation to each img
In js set animation-delay and increase the time one by one
var DealerCards=document.getElementById("cards");
DealerCards.innerHTML = "";
var DealerArray=[1,1,1];
for (var i = 0; i < DealerArray.length; i++) {
var Dealercard = document.createElement('img');
var random = Math.floor((Math.random() * 10));
Dealercard.setAttribute("width", 50);
Dealercard.setAttribute("src","jj");
Dealercard.style.animationDelay=(i + 0.5 )+'s';
DealerCards.appendChild(Dealercard);
}
DealerCards.className = 'myDIV';
.myDIV img{
border: 0px;
width: 50px;
animation: mymove 1s;
background-color:transparent;
color: transparent;
}
myDiv {
display:flex;
}
#keyframes mymove {
50% {
transform: rotateY(180deg);
}
}
<div id="cards"></div>

Related

how to show text on the same cell containing an image on the top of it after an onclick event

I have an onclick event on every cell which contains an image.
After clicking on the cell, the image scales up an rotates by some angle specified.
I want the image to fade out and I want the description of the anime which is text to appear on the image. If I click again the same cell the text should fade out and the cell must return back as it was in the first place.
(I will accept it even if it can be done through a button event, but the button should be in the same cell. PLEASE TRY TO SOLVE THIS USING JAVASCRIPT WITHOUT USING ANY LIBRARIES OR FRAMEWORKS IF U CAN.)
<!--BODY OF THE HTML PAGE-->
<body>
<div class="c1" onclick="f(this)">
<img src="https://picsum.photos/200">
</div>
</body>
<!--CSS AND SCRIPT OF THE HTML PAGE-->
<style type="text/css">
.c1
{
background-color: blue;
width: 200px;
height: 200px;
position: absolute;
left:40%;
top: 30%;
transform: rotateZ(-45deg);
}
</style>
<script type="text/javascript">
timesclicked = 0;
function f(obj) {
timesclicked+=1;
if(timesclicked%2!=0)
{
obj.style.transform = 'scale(2) rotateZ(-90deg) ';
obj.style.transition = 'all 1s 0.3s';
}
else
{
obj.style.transform = 'scale(1) rotateZ(-45deg)';
obj.style.transition = 'all 1s 0.3s';
}
}
</script>
let timesclicked = 0;
function f(containerObj, spinningTime) {
timesclicked += 1;
for(let cell of containerObj.getElementsByTagName('div')){
if (timesclicked % 2 != 0) {
cell.style.transform = 'scale(1.2) rotateZ(0deg) ';
cell.style.transition = 'all 1s ' + spinningTime + 's';
setTimeout(() => {
cell.innerHTML = '<div> Data about the image Data about the image Data about the image Data about the image Data about the image Data about the image Data about the image Data about the image Data about the image Data about the image</div>'
}, spinningTime * 1000);
} else {
cell.style.transform = 'scale(1) rotateZ(-315deg)';
cell.style.transition = 'all 1s ' + spinningTime + 's';
setTimeout(() => {
cell.innerHTML = '<img src="https://picsum.photos/200">';
}, spinningTime * 1000);
}
}
}
.c1 {
background-color: blue;
width: 150px;
height: 150px;
margin: 10px;
transform: rotateZ(-45deg);
}
.container {
display: flex;
}
<div class="container" id="container">
<div class="c1" onclick="f(container,0.3)">
<img src="https://picsum.photos/200">
</div>
<div class="c1" onclick="f(container,0.3)">
<img src="https://picsum.photos/200">
</div>
<div class="c1" onclick="f(container,0.3)">
<img src="https://picsum.photos/200">
</div>
</div>
HTML:
<div class="container c1" onclick="f(this)">
<img src="https://picsum.photos/200">
<div style="display:none; color:white;" class="centered">Your info</div>
</div>
CSS:
/* Centered text */
.centered {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.c1 {
background-color: blue;
width: 200px;
height: 200px;
position: absolute;
left: 40%;
top: 30%;
transform: rotateZ(-45deg);
}
JS:
let timesclicked = 0;
function f(obj) {
timesclicked += 1;
if (timesclicked % 2 != 0) {
obj.style.transform = 'scale(2) rotateZ(-90deg) ';
obj.style.transition = 'all 1s 0.3s';
obj.children[1].style.transform = 'scale(2) rotateZ(-270deg) ';
obj.children[1].style.display = "";
} else {
obj.style.transform = 'scale(1) rotateZ(-45deg)';
obj.style.transition = 'all 1s 0.3s';
obj.children[1].style.display = "none";
}
}

RotateY of a group of divs dynamically

I'm working on this script since 9 days, I found the script online, and from there I tried to add some code.
The point of the script is to rotate the Div dynamically based on the distance they have between each other.
In a way it works, if you resize the page at some point the divs turn their Y axes.
I have mainly 2 problems, the first one is that if I add new divs they just are shown in a new line.
The second problem is that those divs position should change, they need to get closer and they should move to the left side of the div.
I hope somebody can help because I spent already 10 days on this and I can't find a solution.
Thank you so much
function myFunction(distance) {
//add browser check currently it set for safari
// Code for Safari
var degree = 0;
if (distance <= -1 && distance >= -5) {
degree = 15;
} else if (distance < -5 && distance >= -10) {
degree = 25;
} else if (distance < -10 && distance >= -15) {
degree = 30;
} else if (distance < -15 && distance >= -20) {
degree = 35;
} else if (distance < -20) {
degree = 45;
}
document.getElementById("panel").style.WebkitTransform = "rotateY(" + degree + "deg)";
document.getElementById("panel2").style.WebkitTransform = "rotateY(" + degree + "deg)";
document.getElementById("panel3").style.WebkitTransform = "rotateY(" + degree + "deg)";
document.getElementById("panel4").style.WebkitTransform = "rotateY(" + degree + "deg)";
// document.getElementById("panel").style.marginRight= "100px";
document.getElementById("panel2").style.marginRight = "300px";
document.getElementById("panel3").style.marginRight = "30px";
document.getElementById("panel4").style.marginRight = "30px";
// document.getElementById("panel5").style.WebkitTransform = "rotateY(45deg)";
// document.getElementById("panel6").style.WebkitTransform = "rotateY(45deg)";
// Code for IE9
// document.getElementById("asd").style.msTransform = "rotateY(20deg)";
// Standard syntax
// document.getElementById("asd").style.transform = "rotateY(20deg)";
}
function myFunctionb() {
document.getElementById("panel").style.WebkitTransform = "rotateY(0deg)";
document.getElementById("panel2").style.WebkitTransform = "rotateY(0deg)";
document.getElementById("panel3").style.WebkitTransform = "rotateY(0deg)";
document.getElementById("panel4").style.WebkitTransform = "rotateY(0deg)";
// document.getElementById("panel5").style.WebkitTransform = "rotateY(0deg)";
// document.getElementById("panel6").style.WebkitTransform = "rotateY(0deg)";
}
// need to find a better solution
var first = document.getElementById("panel");
var second = document.getElementById("panel2");
var lastpanel = document.getElementById("panel4");
var lastbox = document.getElementById("last");
var container = document.getElementById("wrapper");
var notcongainer = container.offsetLeft;
var distance = container.offsetWidth - (lastpanel.offsetWidth + lastbox.offsetLeft + 4) + notcongainer;
console.log(distance);
var myVar;
var minDistance = 10;
function check() {
myVar = setInterval(testcheck, 100);
}
// First I check that the boxes lenght are as much as the container
// Then I check the distance between 2 boxes
function testcheck() {
if (distance < minDistance) {
myFunction(distance);
} else {
myFunctionb();
}
distance = container.offsetWidth - (lastpanel.offsetWidth + lastbox.offsetLeft + 4) + notcongainer;
/*console.log(distance)*/
}
//ADD NEW DIV
function addDiv() {
var div = document.createElement('div');
div.className = "col-box";
div.id = "newId";
div.innerHTML = '<div class="hover panel"><div id= "panel3" class="front"><div class="box1"><p>New Div</p></div></div></div>';
document.getElementById('wrapper').appendChild(div);
}
body {
background-color: #ecf0f1;
margin: 20px;
font-family: Arial, Tahoma;
font-size: 20px;
color: #666666;
text-align: center;
}
p {
color: #ffffff;
}
.col-box {
width: 22%;
position: relative;
display: inline;
display: inline-block;
margin-bottom: 20px;
z-index: 1;
}
.end {
margin-right: 0 !important;
}
/*-=-=-=-=-=-=-=-=-=-=- */
/* Flip Panel */
/*-=-=-=-=-=-=-=-=-=-=- */
.wrapper {
width: 80%;
height: 200px;
margin: 0 auto;
background-color: #bdd3de;
hoverflow: hidden;
border: 1px;
}
.panel {
margin: 0 auto;
height: 130px;
position: relative;
-webkit-perspective: 600px;
-moz-perspective: 600px;
}
.panel .front {
text-align: center;
}
.panel .front {
height: inherit;
position: absolute;
top: 0;
z-index: 900;
text-align: center;
-webkit-transform: rotateX(0deg) rotateY(0deg);
-moz-transform: rotateX(0deg) rotateY(0deg);
-webkit-transform-style: preserve-3d;
-moz-transform-style: preserve-3d;
-webkit-backface-visibility: hidden;
-moz-backface-visibility: hidden;
-webkit-transition: all .4s ease-in-out;
-moz-transition: all .4s ease-in-out;
-ms-transition: all .4s ease-in-out;
-o-transition: all .4s ease-in-out;
transition: all .4s ease-in-out;
}
.panel.flip .front {
-webkit-transform: rotateY(45deg);
-moz-transform: rotateY(180deg);
}
.col-box:hover {
z-index: 1000;
}
.box1 {
background-color: #14bcc8;
width: 160px;
height: 60px;
margin-left: 5px;
padding: 20px;
border-radius: 10px;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
}
<body onload="check()">
<div id="wrapper" class="wrapper">
<div id="first" class="col-box">
<div class="hover panel">
<div id="panel" class="front">
<div class="box1">
<p>Div 1</p>
</div>
</div>
</div>
</div>
<div id="second" class="col-box">
<div class="hover panel">
<div id="panel2" class="front">
<div class="box1">
<p>Div 2</p>
</div>
</div>
</div>
</div>
<div id="third" class="col-box">
<div class="hover panel">
<div id="panel3" class="front">
<div class="box1">
<p>Div 3</p>
</div>
</div>
</div>
</div>
<div id="last" class="col-box">
<div class="hover panel">
<div id="panel4" class="front">
<div class="box1">
<p>Last Div</p>
</div>
</div>
</div>
</div>
<button onclick="addDiv()">Add New Div</button>
</div>
9 days... that's too long. Time to step back and break this up into smaller things.
This isn't an 'answer' yet... but I need to post an image for you. Your question wasn't that clear, but it's not an easy thing to explain. In your case, I would show an image.
Now that I can see what you're doing - it doesn't sound like an arbitrary and completely silly task.
You have a list of 'things' or 'cards' or whatever... so, first things first... how do you insert new DOM into the page - and / into that list - and have the list all on one line. A few ways - but most likely you can just use flexbox -
https://jsfiddle.net/sheriffderek/8eLggama -> https://jsfiddle.net/sheriffderek/pztvhn3L (this is an example - but it's pretty naive - and the further you take this, the closer you'll get to building what most frameworks - like Vue could do way better... but good for learning! Start with something small - to just do that.
// will take an object with the list name and the card id
// eventuallly - you'd want the card to have more info sent in...
function addCard(infoObject) {
var targetList = document.getElementById(infoObject.list);
var li = document.createElement('li');
li.classList.add('item');
// ug! why aren't I using jQuery...
var component = document.createElement('aside');
component.classList.add('card');
var title = document.createElement('h2');
var uniqueId = idMaker.create();
var id = document.createTextNode(uniqueId);
title.appendChild(id);
component.appendChild(title)
li.appendChild(component);
targetList.appendChild(li);
// woah... this part is really boring...
// this is why templating engines and JSON are so popular
// you could also add 'remove' button etc... right?
var removeButton = document.createElement('button');
var removeText = document.createTextNode('x');
removeButton.appendChild(removeText);
removeButton.classList.add('remove-card');
component.appendChild(removeButton);
//
removeButton.addEventListener('click', function() {
var parent = document.getElementById(infoObject.list);
idMaker.removed.push(uniqueId);
parent.removeChild(li);
idMaker.read();
});
}
// start out with a few?
addCard({list: 'exampleTarget'});
addCard({list: 'exampleTarget'});
addCard({list: 'exampleTarget'});
// start a UI to add cards
var addCardButton = document.querySelector('[data-trigger="add-card"]');
addCardButton.addEventListener('click', function() {
addCard({list: 'exampleTarget'});
});
...and then you maybe absolute position the card inside of that list item? It's certainly a unique thing to do, and wont be easy. Then, you can check the number of items - of the width of each item - and make a calculation for transform based on that? Good luck!

Add transition css to image slider

I have a slider with 3 images and 3 buttons which change the current image 'src' attribute (and hence change the current image), but now I want to add a smooth transition when I change the image and I would like to get this using css transitions.
So when I click on any bullet I need the current image fades out and then the new image fades in. how can I do this?
var listItemContainer = document.getElementById('carousel-index');
var imageChanger = document.getElementById('image-container').getElementsByTagName('img');
var bulletNumber;
for (i = 0; i < listItemContainer.children.length; i++){
(function(index){
listItemContainer.children[i].onclick = function(){
bulletNumber = index;
imageChanger[0].setAttribute('src', 'https://civilian-interviewe.000webhostapp.com/img/mini_slider_' + (bulletNumber+1) + '.png');
}
})(i);
};
body{
text-align:center;
}
#carousel-index{
margin:0;
padding:0;
}
#carousel-index li {
display: inline-block;
width: 2em;
height: 2em;
border-radius: 100%;
background-color: #666;
cursor: pointer;
}
<div id="image-container">
<img src="https://civilian-interviewe.000webhostapp.com/img/mini_slider_1.png"/>
<ul id="carousel-index">
<li></li>
<li></li>
<li></li>
</ul>
</div>
Here is a CODEPEN
PD: I want to do this without Jquery.
CodePen sample
I've added some css transitions to the css
div#image-container {
opacity:1;
-webkit-transition: opacity 1s;
-moz-transition: opacity 1s;
transition: opacity 1s;
}
div#image-container.fade {
opacity:0;
}
and some function to handle the event:
var image = document.getElementById('image-container');
if(image.className === 'fade'){
image.className = '';
setTimeout(function(){
image.className = 'fade';
},1000)
}else{
image.className = 'fade';
setTimeout(function(){
image.className = '';
},1000)
}
setTimeout(function(){
bulletNumber = index;
imageChanger[0].setAttribute('src', 'https://civilian-interviewe.000webhostapp.com/img/mini_slider_' + (bulletNumber+1) + '.png');
},1000);
use CSS3 animation with add class in javascript
var listItemContainer = document.getElementById('carousel-index');
var imageChanger = document.getElementById('image-container').getElementsByTagName('img');
var bulletNumber;
for (i = 0; i < listItemContainer.children.length; i++) {
(function(index) {
listItemContainer.children[i].onclick = function() {
bulletNumber = index;
imageChanger[0].className = "hide";
setTimeout(function(){
imageChanger[0].setAttribute('src', 'https://civilian-interviewe.000webhostapp.com/img/mini_slider_' + (bulletNumber + 1) + '.png');
},501);
setTimeout(function(){
imageChanger[0].className = "show";
}, 1001);
}
})(i);
};
body {
text-align: center;
}
#carousel-index {
margin: 0;
padding: 0;
}
#carousel-index li {
display: inline-block;
width: 2em;
height: 2em;
border-radius: 100%;
background-color: #666;
cursor: pointer;
}
#image-container img.show {
animation: show .5s;
animation-fill-mode: both;
}
#keyframes show {
from {
transform:scale(0.7);
opacity:0
}
to {
transform: scale(1);
opacity:1
}
}
#image-container img.hide {
animation: hide .5s;
animation-fill-mode: both;
}
#keyframes hide {
from {
transform:scale(1);
opacity:1
}
to {
transform:scale(0.7);
opacity:0
}
}
<div id="image-container">
<img src="https://civilian-interviewe.000webhostapp.com/img/mini_slider_1.png" />
<ul id="carousel-index">
<li></li>
<li></li>
<li></li>
</ul>
</div>
You can use CSS transition, and i guess that desired property is opacity.
var listItemContainer = document.getElementById('carousel-index');
var imageChanger = document.getElementById('image-container').getElementsByTagName('img');
var bulletNumber;
imageChanger[0].classList.add('fadeIn');
for (i = 0; i < listItemContainer.children.length; i++){
(function(index){
listItemContainer.children[i].onclick = function(){
bulletNumber = index;
imageChanger[0].classList.remove('fadeIn');
setTimeout(function(){
imageChanger[0].classList.add('fadeIn');
} , 100);
imageChanger[0].setAttribute('src', 'https://civilian-interviewe.000webhostapp.com/img/mini_slider_' + (bulletNumber+1) + '.png');
}
})(i);
};
body{
text-align:center;
}
#carousel-index{
margin:0;
padding:0;
}
#carousel-index li {
display: inline-block;
width: 2em;
height: 2em;
border-radius: 100%;
background-color: #666;
cursor: pointer;
}
img {
opacity:0;
}
img.fadeIn {
opacity:1;
transition:opacity 0.5s ease;
}
<div id="image-container">
<img src="https://civilian-interviewe.000webhostapp.com/img/mini_slider_1.png"/>
<ul id="carousel-index">
<li></li>
<li></li>
<li></li>
</ul>
</div>
Start image opacity should be 0, of course:
img {
opacity:0;
}
img.fadeIn {
opacity:1;
transition:opacity 0.5s ease;
}
And then, on click (remove added class -> set opacity to 0 again), and add it again. You can play with values to get desired effect.
EDIT: fadeOut/fadeIn... it was little tricky, because of one container, and img src changing, but additional timeout solves it:
var listItemContainer = document.getElementById('carousel-index');
var imageChanger = document.getElementById('image-container').getElementsByTagName('img');
var bulletNumber;
imageChanger[0].classList.add('fadeIn');
for (i = 0; i < listItemContainer.children.length; i++){
(function(index){
listItemContainer.children[i].onclick = function(){
bulletNumber = index;
imageChanger[0].classList.remove('fadeIn');
imageChanger[0].classList.add('fadeOut');
setTimeout(function(){
imageChanger[0].classList.add('fadeIn');
imageChanger[0].classList.remove('fadeOut');
} , 1000);
setTimeout(function(){
imageChanger[0].setAttribute('src', 'https://civilian-interviewe.000webhostapp.com/img/mini_slider_' + (bulletNumber+1) + '.png');
} , 1000);
}
})(i);
};
body{
text-align:center;
}
#carousel-index{
margin:0;
padding:0;
}
#carousel-index li {
display: inline-block;
width: 2em;
height: 2em;
border-radius: 100%;
background-color: #666;
cursor: pointer;
}
img {
opacity:0;
}
img.fadeIn {
opacity:1;
transition:opacity 0.5s ease;
}
img.fadeOut {
opacity:0;
transition:opacity 0.5s ease;
}
<div id="image-container">
<img src="https://civilian-interviewe.000webhostapp.com/img/mini_slider_1.png"/>
<ul id="carousel-index">
<li></li>
<li></li>
<li></li>
</ul>
</div>
P.S. Images should be probably preloaded, in order to all work fine on first load.
One more alternative, JS based, didn't change HTML or CSS (explanation as comments in the code):
var listItemContainer = document.getElementById('carousel-index');
var imageChanger = document.getElementById('image-container').getElementsByTagName('img')[0];
var newSrc, fadeDelta=-0.01; //don't change 'delta', change 'fadeoutDelay' and 'fadeinDelay'
(function initImageChanger(i,count){
imageChanger.style.opacity = 1; //set opacity in JS, otherwise the value returns "" (empty)
listItemContainer.children[i].onclick = function(){
var fadeoutDelay=5, fadeinDelay=15, opacity=parseFloat(imageChanger.style.opacity); //change delays to alter fade-speed
function changeSrc(){
var src = imageChanger.getAttribute('src');
var ext = src.substring(src.lastIndexOf('.')); //store extension
src = src.substring(0,src.lastIndexOf('_')+1); //store source up to the identifying number
return src+i+ext; //combine parts into full source
}
function fade(delay){
imageChanger.style.opacity = (opacity+=fadeDelta);
if (fadeDelta<0 && opacity<=0){ //fade-out complete
imageChanger.setAttribute('src',newSrc);
fadeDelta*=-1, delay=fadeinDelay; //invert fade-direction
} else if (fadeDelta>0 && opacity>=1){newSrc=null, fadeDelta*=-1; return;} //fade-in complete, stop function
setTimeout(function(){fade(delay);},delay);
}
//start fade, but only if image isn't already fading, otherwise only change source (and reset)
if (changeSrc() != imageChanger.getAttribute('src')){
newSrc=changeSrc();
if (opacity==0 || opacity==1){fade(fadeoutDelay);}
else if (fadeDelta>0){fadeDelta *= -1;} //reset fade for new source
}
};
if (++i < count){initImageChanger(i,count);} //iterate to next element
})(0,listItemContainer.children.length); //supply start-arguments
body {text-align:center;}
#image-container img {width:auto; height:150px;}
#carousel-index {margin:0; padding:0;}
#carousel-index li {display:inline-block; width:2em; height:2em; border-radius:100%; background-color:#666; cursor:pointer;}
<div id="image-container">
<img src="https://civilian-interviewe.000webhostapp.com/img/mini_slider_1.png"/>
<ul id="carousel-index"><li></li><li></li><li></li></ul>
</div>
codepen: http://codepen.io/anon/pen/xgwBre?editors=0010
It's not a perfect solution, but here's one way of doing it without jQuery:
First create a new function:
function fadeChange(element) {
var op = 0.1;
var timer = setInterval(function () {
if (op >= 1){
clearInterval(timer);
}
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ")";
op += op * 0.1;
}, 10);
}
Then call that function when setting the new image:
fadeChange(imageChanger[0]);
This is demonstrated through the updated codepen here.
It's a bit clunky, but does fade the images. You may want to consider using a single image for the monitor, and then simply changing the contents of the monitor through this method.

Simon Game : Two colors in a row won't fade properly

I'm trying to build a javascript 'Simon says' game.
So far, I made some basic tests with buttons.
First button 'Start' generates a sequence. Second button 'Show' will show what was generated.
Everything works except when the same color, in the random generated sequence, appears in a row.
Ex: = [ 'blue', 'yellow', 'yellow']
Only in this case the fade-in / fade-out effect won't work.
I checked with DevTools, what was wrong and it seems that the loop adds the class 'fade-out' to both indexes (in the case above..to index 1 and 2).
Why is that? And how can I fix it?
HTML
<div id="container">
<div id="blue" class="btn"></div>
<div id="red" class="btn"></div>
<div id="yellow" class="btn"></div>
<div id="green" class="btn"></div>
</div>
<button id="startBtn">Start</button>
<button id='showMe'>Show</button>
CSS
.btn {
height: 100px;
width: 25vw;
border: 1px solid black;
opacity: 1;
transition: opacity 1s ease;
}
.fade-out {
opacity: 0.5;
transition: opacity 1s ease;
}
#container {
display: flex;
flex-wrap: nowrap;
}
#blue {
background-color: blue;
}
#yellow {
background-color: yellow;
}
#red {
background-color: red;
}
#green {
background-color: green;
}
JS
var color = container.querySelectorAll('div.btn');
var startBtn = document.getElementById('startBtn');
var showBtn = document.getElementById('showMe');
var pcSequence = [],
mySequence = [],
i,
theLoop;
startBtn.addEventListener('click', oneMore, false);
showBtn.addEventListener('click', showSeq, false);
function oneMore(){
pcSequence.push(color[Math.floor(Math.random() * 4)]);
}
function showSeq(){
i = 0;
theLoop = setInterval(function(){
if (i > 0){ pcSequence[i - 1].classList.remove('fade-out'); }
if (i >= pcSequence.length){
clearInterval(theLoop);
} else {
pcSequence[i].classList.add('fade-out');
}
i++;
}, 2000);
}
While I am not seeing the problem with fade-out appearing on two of the squares, I do see that, for example, in your case of blue, yellow, yellow, the yellow isn't doesn't become unfaded-out at all.
If that is the problem you are concerned about, the reason is that you are removing the class and then immediately re-adding it, so the ui is essentially not doing the fade-in.
Another strategy here might be to use the transitionend event to do the fade in, rather than doing that in the interval. Something like this (I put a hack in to force the red and yellow to be set each time):
var color = container.querySelectorAll('div.btn');
var startBtn = document.getElementById('startBtn');
var showBtn = document.getElementById('showMe');
var pcSequence = [],
mySequence = [],
i,
theLoop;
startBtn.addEventListener('click', oneMore, false);
showBtn.addEventListener('click', showSeq, false);
// Force red initially
pcSequence.push(color[1]);
function oneMore(){
// Force yellow each time they press Start
pcSequence.push(color[2]);
//Math.floor(Math.random() * 4)]);
}
function clearTransition() {
var colorSquare = pcSequence[i - 1];
colorSquare.removeEventListener('transitionend', clearTransition);
colorSquare.classList.remove('fade-out');
}
function showSeq(){
i = 0;
theLoop = setInterval(function(){
if (i >= pcSequence.length){
clearInterval(theLoop);
} else {
var colorSquare = pcSequence[i];
colorSquare.classList.add('fade-out');
colorSquare.addEventListener('transitionend', clearTransition);
}
i++;
}, 2000);
}
.btn {
height: 100px;
width: 25vw;
border: 1px solid black;
opacity: 1;
transition: opacity 1s ease;
}
.fade-out {
opacity: 0.5;
transition: opacity 1s ease;
}
#container {
display: flex;
flex-wrap: nowrap;
}
#blue {
background-color: blue;
}
#yellow {
background-color: yellow;
}
#red {
background-color: red;
}
#green {
background-color: green;
}
<div id="container">
<div id="blue" class="btn"></div>
<div id="red" class="btn"></div>
<div id="yellow" class="btn"></div>
<div id="green" class="btn"></div>
</div>
<button id="startBtn">Start</button>
<button id='showMe'>Show</button>

Vertical distribution of elements (and animation) - jQuery

I like to know the cleanest method to distribute elements vertically with jQuery. I nailed it but it's not very clean right >< ? I would like to get to do it without plugin... Thank you in advance ;-)
Here my JSFiddle
jQuery(document).ready(function($) {
var gap = 10;
var firstElem = $('#lorem');
if(firstElem.length){
var heightCall = (firstElem.offset().top)+(firstElem.outerHeight())+(gap);
var middleElem = $('#dolore');
middleElem.offset({top : heightCall});
var lastElem = $('#amet');
var NewHeightCall = (middleElem.offset().top)+(middleElem.outerHeight())+(gap);
lastElem.offset({top : NewHeightCall});
/* Animation */
$('#lorem, #dolore, #amet').hover(
function(){
$(this).stop().animate({left: (($(this).offset().left)-(20))+'px',opacity:'0.5'},'slow')
},
function(){
$(this).stop().animate({left: (($(this).offset().left)+(20))+'px',opacity:'1'},'slow')
});
}
});
I have fiddled around with your code:
This is a simplified version:
HTML:
<div id="lorem" class="vertical-block">My first ID div</div>
<div id="dolore" class="vertical-block">My second ID div.<br>My second ID div. My second ID div.</div>
<div id="amet" class="vertical-block">My third ID div</div>
CSS:
.vertical-block {
position: absolute;
padding:15px;
}
#lorem{
top:20%;
right:40px;
background:#f79673;
}
#dolore{
right:80px;
background:#cd7454;
}
#amet{
right:40px;
background:#a15338;
}
.vertical-block:hover {
opacity: 0.5;
padding-right: 30px;
-webkit-transition: all 2s;
transition: all 0.4s;
}
Javascript:
jQuery(document).ready(function($) {
var gap = 10;
var firstElem = $('#lorem');
var top = 0;
$('.vertical-block').each(function(element){
var $currentElement = $(this);
if (top === 0) {
top = $currentElement.offset().top + $currentElement.outerHeight() + gap;
} else {
$currentElement.offset({top: top});
top = top + $currentElement.outerHeight() + gap;
}
});
});
https://jsfiddle.net/rae2x4e0/1/
Now if you want to go for a purely css solution, then:
HTML:
<div class="container">
<div id="lorem" class="vertical-block">My first ID div</div>
<br />
<div id="dolore" class="vertical-block">My second ID div.<br>My second ID div. My second ID div.</div>
<br />
<div id="amet" class="vertical-block">My third ID div</div>
</div>
CSS:
.container {
position-relative;
text-align: right;
padding-top: 10%;
}
.vertical-block {
padding:15px;
display: inline-block;
margin-top: 20px;
}
#lorem{
right:40px;
background:#f79673;
}
#dolore{
right:80px;
background:#cd7454;
}
#amet{
right:40px;
background:#a15338;
}
.vertical-block:hover {
opacity: 0.5;
padding-right: 30px;
-webkit-transition: all 2s;
transition: all 0.4s;
}
https://jsfiddle.net/ycdwpjxw/1/

Categories

Resources