Using bounce animation on a scaled element - javascript

What is the best way to have something scale and then perform a bounce animation at that scale factor before going back to the original scale factor. I realize I could do something like scaling it to 2.2, then 1.8, then 2.0, but I'm looking for a way where you just have to perform the bounce animation on the scale factor because my scale factor will change. Here is my example. Basically I want to combine the two to work like I said but as you can see the bounce animation performs based off the div size prior to scaling. P.S I want this done in one action, the two buttons were just for the example.
function myFunction() {
var image = document.getElementById('test');
image.style.WebkitTransform = ('scale(2,2)');
}
function myFunction2() {
var image = document.getElementById('test');
image.classList.remove('bounce');
image.offsetWidth = image.offsetWidth;
image.classList.add('bounce') ;
}
div#test {
position:relative;
display: block;
width: 50px;
height: 50px;
background-color: blue;
margin: 50px auto;
transition-duration: 1s;
}
.bounce {
animation: bounce 450ms;
animation-timing-function: linear;
}
#keyframes bounce{
25%{transform: scale(1.15);}
50%{transform: scale(0.9);}
75%{transform: scale(1.1);}
100%{transform: scale(1.0);}
}
<div id='test'> </div>
<button class = 'butt' onclick = 'myFunction()'>FIRST</button>
<button class = 'butt' onclick = 'myFunction2()'>SECOND</button>

Just a series of jquery animations that change by a set number of pixels should do the trick. You could always use something like parseInt($('#test').css('width')) in the math for how much to change if you want scaled-up objects to bounce more/less
function scaleUp() {
var image = document.getElementById('test');
image.style.WebkitTransform = ('scale(2,2)');
}
function bounce() {
$('#test').animate({
'width': "-=20",
'height': "-=20"
}, 150);
$('#test').animate({
'width': "+=30",
'height': "+=30",
}, 150);
$('#test').animate({
'width': "-=20",
'height': "-=20",
}, 150);
$('#test').animate({
'width': "+=10",
'height': "+=10",
}, 150);
}
div#test {
position:relative;
display: block;
width: 50px;
height: 50px;
background-color: blue;
margin: 50px auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='test'> </div>
<button class = 'butt' onclick = 'bounce()'>Bouncey</button>
<button class = 'butt' onclick = 'scaleUp()'>Scale up bouncey</button>
Here's them combined into one with an animation for growing / shrinking:
function scaleUp() {
var image = document.getElementById('test');
image.style.WebkitTransform = ('scale(2,2)');
}
function bounce() {
const width = parseInt($('#test').css('width'));
const height = parseInt($('#test').css('height'));
$('#test').animate({
'width': parseInt($('#test').css('width'))*2.2,
'height': parseInt($('#test').css('height'))*2.2
}, 300);
$('#test').animate({
'width': "-=20",
'height': "-=20"
}, 150);
$('#test').animate({
'width': "+=30",
'height': "+=30",
}, 150);
$('#test').animate({
'width': "-=20",
'height': "-=20",
}, 150);
$('#test').animate({
'width': "+=10",
'height': "+=10",
}, 150);
$('#test').animate({
'width': width,
'height': height
}, 300);
}
div#test {
position:relative;
display: block;
width: 50px;
height: 50px;
background-color: blue;
margin: 50px auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='test'> </div>
<button class = 'butt' onclick = 'bounce()'>Bouncey</button>

Related

Trigger an alert when a css-width-style animated with transitions reaches 0

I'm making a simple game where there are colored bars that slowly drop to zero. The player must click the "refill" button before any bar drops to zero or they lose. Initially I tried doing some time outs and things to try and just get the alerts to show up when needed, but they were showing up the second the width css style started its transition to 0, which isn't what I wanted. Even putting delays on it wasn't working.
So instead I started looking at the pixel width of the blueBar css style to try and trigger the alert when that is zero. I am able to get the alert to show up when I manually set the width to zero, but it doesn't seem to keep up with the changing width. Is there a way to get the variable blueWidth to continuously check its value so that an alert can be triggered when it equals 0?
$(document).ready(function(){
// Locate the main items in the page
var blueButton = $('#blue-button');
var blueBar = $('#blue-bar');
var yellowButton = $('#yellow-button');
var yellowBar = $('#yellow-bar');
// triggers auto-decay of the blue bar
blueBar.delay(2000).queue(function(){
blueBar.css({'width': '0%', 'transition': 'width 5s linear'});
});
// refills blue bar on click, then auto-decay it after set timeout
blueButton.click(function() {
blueBar.css({'width': '100%', 'transition': 'width 0.5s linear'});
setTimeout(function(){
blueBar.css({'width': '0%', 'transition': 'width 5s linear'})
}, 2000);
});
// checks to see if blue bar zeroes out
var blueWidth = parseInt(blueBar.css('width').slice(0,-2));
console.log(blueWidth);
if(blueWidth <= 0){
alert('you lose :(');
}
// triggers auto-decay of the yellow bar
yellowBar.delay(3000).queue(function(){
yellowBar.css({'width': '0%', 'transition': 'width 2.5s linear'});
});
// refills yellow bar on click, then auto-decay it after set timeout
yellowButton.click(function() {
yellowBar.css({'width': '100%', 'transition': 'width 0.5s linear'});
setTimeout(function(){
yellowBar.css({'width': '0%', 'transition': 'width 2.5s linear'})
}, 3000);
});
});
.game {
text-align: center;
}
div {
margin: 20px 0px;
}
.empty {
width: 160px;
height: 11px;
border-radius: 11px;
margin: auto;
background: #f1f1f1;
}
.blue {
width: 100%;
height: 11px;
border-radius: 11px;
background: #bfe5ff;
}
.yellow {
width: 100%;
height: 11px;
border-radius: 11px;
background: #f8d975;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="game">
<div>
<div class="empty">
<div id="blue-bar" class="blue"></div>
</div>
<button id="blue-button">refill</button>
</div>
<div>
<div class="empty">
<div id="yellow-bar" class="yellow"></div>
</div>
<button id="yellow-button">refill</button>
</div>
</div>
You can use setInterval function like this :
$(document).ready(function() {
// Locate the main items in the page
var blueButton = $('#blue-button');
var blueBar = $('#blue-bar');
var yellowButton = $('#yellow-button');
var yellowBar = $('#yellow-bar');
// triggers auto-decay of the blue bar
blueBar.delay(2000).queue(function() {
blueBar.css({
'width': '0%',
'transition': 'width 5s linear'
});
});
// refills blue bar on click, then auto-decay it after set timeout
;
blueButton.click(function() {
blueBar.css({
'width': '100%',
'transition': 'width 0.5s linear'
});
setTimeout(function() {
blueBar.css({
'width': '0%',
'transition': 'width 5s linear'
})
}, 2000);
});
// checks to see if blue bar zeroes out
setInterval(function() {
var blueWidth = parseInt(blueBar.css('width').slice(0, -2));
if (blueWidth <= 0) {
console.log('you lose because of blue:(');
}
}, 300);
// triggers auto-decay of the yellow bar
yellowBar.delay(3000).queue(function() {
yellowBar.css({
'width': '0%',
'transition': 'width 2.5s linear'
});
});
// refills yellow bar on click, then auto-decay it after set timeout
yellowButton.click(function() {
yellowBar.css({
'width': '100%',
'transition': 'width 0.5s linear'
});
setTimeout(function() {
yellowBar.css({
'width': '0%',
'transition': 'width 2.5s linear'
})
}, 3000);
});
setInterval(function() {
var yellowWidth = parseInt(yellowBar.css('width').slice(0, -2));
if (yellowWidth <= 0) {
console.log('you lose because of yellow:(');
}
}, 300);
});
.game {
text-align: center;
}
div {
margin: 20px 0px;
}
.empty {
width: 160px;
height: 11px;
border-radius: 11px;
margin: auto;
background: #f1f1f1;
}
.blue {
width: 100%;
height: 11px;
border-radius: 11px;
background: #bfe5ff;
}
.yellow {
width: 100%;
height: 11px;
border-radius: 11px;
background: #f8d975;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="game">
<div>
<div class="empty">
<div id="blue-bar" class="blue"></div>
</div>
<button id="blue-button">refill</button>
</div>
<div>
<div class="empty">
<div id="yellow-bar" class="yellow"></div>
</div>
<button id="yellow-button">refill</button>
</div>
</div>

simple autoslider with javascript but Setinterval?

i write some codes for my simple slider but some things run wrong
i want to reset canvasHeight
var myVar = setInterval(function(){ myTimer() }, 1000);
function myTimer() {
img.css({'top':- (height -canvasHeight) })
canvasHeight+=100
var top = img.css('top')
if (top == '0px'){
myStopFunction()
img.css({'top':-height})
canvasHeight = 0
canvasHeight+=100
height = new $('img').height() - canvasHeight;
setInterval(function(){ myTimer() }, 1000);
}
}
function myStopFunction() {
clearInterval(myVar);
}
https://jsfiddle.net/n1uzy4u3/
You're not assigning the setInterval that restarts it to the myVar variable, so the next time you try to clear it, it's still using the interval ID from the original call. This causes multiple intervals to be running, and therefore multiple, competing calls of your function.
Also, you've got a bunch of implicit global vars, because you're missing the comma separator.
var img = $('img'),
time = 2000,
top = img.css('top'),
canvasHeight = 100,
height = $('img').height() - canvasHeight;
img.css({
'top': -height
})
var myVar = setInterval(myTimer, 1000);
function myTimer() {
img.css({ 'top': -(height - canvasHeight) })
canvasHeight += 100
var top = img.css('top')
if (top == '0px') {
myStopFunction()
img.css({ 'top': -height })
canvasHeight = 0
canvasHeight += 100
height = new $('img').height() - canvasHeight;
myVar = setInterval(myTimer, 1000);
}
}
function myStopFunction() {
clearInterval(myVar);
}
.box {
position: relative;
width: 320px;
height: 100px;
margin: 0 auto;
overflow: hidden;
}
.scene {
height: 100%;
width: 100%;
float: left;
background-color: #996711;
}
.scene-element {
position: relative;
left: 0;
width: 100%;
height: 100%;
}
.scene-element img {
position: absolute;
-webkit-transition: all ease .8s;
-moz-transition: all ease .8s;
-o-transition: all ease .8s;
transition: all ease .8s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
<div class="scene">
<div class="scene-element">
<img src="https://image.ibb.co/gXKiMR/01.png">
</div>
</div>
</div>
I also removed the anonymous functions you were passing to setInterval. You can just pass the actual function you're calling if there's no other code to run.

Dynamically creating divs with position absolute which can expand to whole screen when clicked

I'm trying to create something like this :
https://tympanus.net/Development/FullscreenLayoutPageTransitions/
But the problem I face is that my divs are dynamic - could be any number that comes from a xhr service call. I'm trying to stack up divs but on click, they don't grow from their position to occupy the whole screen but grow from top left like this:
https://codepen.io/anon/pen/vJPNOq.
How can I achieve the same effect as in the first link for a dynamic list whose count can be unknown?
<div>
<h1>Your dashboard</h1>
<span class="close">X</span>
<section class="parent">
<section>room1</section>
<section>room2</section>
<section>room3</section>
<section>room4</section>
<section>room5</section>
<sectoin>room6</sectoin>
</section>
</div>
section section{
width:150px;
height:150px;
background-color:green;
margin:10px;
padding:30px;
transition:all .5s linear;
}
.parent{
position:relative;
height:100%;
width:100%;
background-color:red;
}
.expanded{
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
z-index:999;
background-color:red;
}
.close{
position:absolute;
top:100;
right:0;
z-index:1000;
cursor:pointer;
}
$('.parent section').click(function(){
$(this).addClass('expanded');
})
$('.close').click(function(){
$('.parent section').each(function(){
$(this).removeClass('expanded');
})
})
Here's a demo that shows how you can do this dynamically, it has a few issues if you spam click it but if you disable the click handler until it finishes the animation, they won't matter. Alternatively you could cache the bounding values (you might want to anyway simply to avoid some of the reflows), but the specifics can change a lot depending on the website you're using this effect on.
Also I didn't implement the shrinking effect but I think it's probably fairly obvious how to do it based on the grow effect.
const numberOfTiles = 9;
const totalColumns = 3;
const totalRows = Math.ceil(numberOfTiles / totalColumns);
const container = document.createElement('div');
Object.assign(container.style, {
width: '80vw',
height: '80vh',
background: 'rgb(60, 61, 60)',
transform: 'translate(10vw, 10vh)',
lineHeight: 1 / totalRows * 100 + '%'
});
const tiles = [];
for (let row = 0; row < totalRows; ++row) {
for (let col = 0; col < totalColumns; ++col) {
if (tiles.length < numberOfTiles) {
const tileContainer = document.createElement('div');
Object.assign(tileContainer.style, {
position: 'relative',
width: 1 / totalColumns * 100 + '%',
height: 1 / totalRows * 100 + '%',
display: 'inline-block'
});
let randomColor = Math.ceil((Math.random() * Math.pow(255, 3))).toString(16);
while (randomColor.length < 6) {
randomColor = '0' + randomColor;
}
randomColor = '#' + randomColor;
const tile = document.createElement('div');
tile.classList.add('tile');
Object.assign(tile.style, {
width: '100%',
height: '100%',
background: randomColor,
willChange: 'transform, left, top'
});
tile.addEventListener('click', (evt) => {
if (tile.classList.toggle('fullscreen')) {
let clientRect = tile.getClientRects();
Object.assign(tile.style, {
position: 'absolute',
width: clientRect.width + 'px',
height: clientRect.height + 'px',
left: clientRect.left + 'px',
top: clientRect.top + 'px',
transition: '1s width, 1s height, 1s transform, 1s left, 1s top',
zIndex: 100
});
setTimeout(() => {
let clientRect = tile.getBoundingClientRect();
Object.assign(tile.style, {
left: 0,
top: 0,
width: '100vw',
height: '100vh',
transform: `translate(${-clientRect.left}px, ${-clientRect.top}px)`
});
}, 0);
} else {
Object.assign(tile.style, {
width: '100%',
height: '100%',
left: 0,
top: 0,
transform: '',
zIndex: 1
});
setTimeout(() => {
Object.assign(tile.style, {
zIndex: 0
});
}, 1000);
}
});
tiles.push(tile);
tileContainer.appendChild(tile);
container.appendChild(tileContainer);
}
}
}
document.body.appendChild(container);
* {
margin: 0;
padding: 0;
}

move box from right to left continously using jquery

i want to move box right then left and again right left continously but it make only one cycle
$(document).ready(function() {
function a() {
$('#foo').css({
'right': window.innerWidth - $('#foo').width(),
'left': 'auto'
}).animate({
'right': '0px'
}, 9000, function() {
$('#foo').animate({
'left': '0px'
}, 9000, a);
});
}
a();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo" style="background: red; width: 100px; height: 100px; position: absolute" ></div>
any help ??
Yes, it works without any problem.
$(document).ready(function() {
function a() {
$('#foo').css({
'right': window.innerWidth - $('#foo').width(),
'left': 'auto'
}).animate({
'right': '0px'
}, 9000, function() {
$('#foo').animate({
'left': '0px'
}, 9000, a);
});
}
a();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo" style="background: red; width: 100px; height: 100px; position: absolute" ></div>
https://jsfiddle.net/n7u7q42d/
Probably you have loaded multiple libraries. Could you post errors please?
Your code already does what you are asking for:
$(document).ready(function() {
function a() {
$('#foo').css({
'right': window.innerWidth - $('#foo').width(),
'left': 'auto'
}).animate({
'right': '0px'
}, 9000, function() {
$('#foo').animate({
'left': '0px'
}, 9000, a);
});
}
a();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo" style="background: red; width: 100px; height: 100px; position: absolute" ></div>
But, you can also accomplish the same thing with much better performance if you use use CSS animations:
#foo {
background: red;
width: 100px;
height: 100px;
position: absolute;
left:0px; /* This is the property that will be animated */
animation:9s leftRight infinite; /* configure the animation */
}
#keyframes leftRight {
0% {
left:0;
}
50% {
left:calc(100% - 100px);
}
100% {
left:0;
}
}
<div id="foo"></div>

This code won't work// How to get the div to slide in-line with other divs on mouse over?

I am aware there are discussions similar and I have read them, analysed them and tried them in my code. The code below is what I currently have, trust me, I have spent all day exhausting all methods to prevent me from asking here but I give up! This is by far the most frustrating goal.
I would like to have a header with a little bar that slides across above each menu item on hover over. A perfect example of what I would like is located here at http://www.wix.com/ . Please visit and move your mouse over the navigation bar and you'll understand instatly what I am trying to achieve.
Here is my current code...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
div {
display: inline-block;
float:left;
}
#red {
background-color:#FF0000;
height:100px;
width:100px;
}
#blue {
background-color:#0000FF;
height:100px;
width:200px;
}
#yellow {
background-color:#E2BE22;
height:100px;
width:50px;
}
#green {
background-color:#008800;
height:100px;
width:170px;
}
#slider{
background-color:#6FF;
height:10px;
width:100px;
position:relative;
}
</style>
</head>
<body>
<div id="slider"></div><br />
<div id="red"></div>
<div id="blue" onmouseover="javascript:movetoblue()" onmouseout="javascript:exitblue()"></div>
<div id="yellow" onmouseover="javascript:movetoyellow()" onmouseout="javascript:exityellow()"></div>
<div id="green" onmouseover="javascript:movetogreen()" onmouseout="javascript:exitgreen()"></div>
</body>
</html>
<script>
var slider = document.getElementById( 'slider' );
function movetoblue(){
var slider = $("#slider");
slider.animate({left: '100px', width: '160px'}, "slow");
}
function exitblue(){
var slider = $("#slider");
slider.animate({left: '7px', width: '200px'}, "slow");
}
function movetoyellow(){
var slider = $("#slider");
slider.animate({left: '100px', width: '160px'}, "slow");
}
function exityellow(){
var slider = $("#slider");
slider.animate({left: '7px', width: '200px'}, "slow");
}
function movetogreen(){
var slider = $("#slider");
slider.animate({left: '100px', width: '160px'}, "slow");
}
function exitgreen(){
var slider = $("#slider");
slider.animate({left: '7px', width: '200px'}, "slow");
}
</script>
I know much is probably wrong with it. Sigh. But any help would be much appreciated. Thank you :)
PS: I would like this to work on Chrome, IE, Safari and Firefox, but I'm mainly concerned about Chrome, IE, Safari. Thanks again!
As I see you are using jQuery but in a very wrong way. I've created a JSFiddle for you. take a look at this
Update 1:
Edited The Code For Better Performance By Adding:
$("#slider").stop()
$(document).ready(function() {
$("#slider").animate({
"left": $(".item:first").position().left + "px",
"width": $(".item:first").width() + "px"
}, 0);
$(".item").hover(function() {
$("#slider").stop()
$("#slider").animate({
"left": $(this).position().left + "px",
"width": $(this).width() + "px"
}, 500);
});
});
div {
display: inline-block;
float: left;
}
#red {
background-color: #FF0000;
height: 100px;
width: 100px;
}
#blue {
background-color: #0000FF;
height: 100px;
width: 200px;
}
#yellow {
background-color: #E2BE22;
height: 100px;
width: 50px;
}
#green {
background-color: #008800;
height: 100px;
width: 170px;
}
#slider {
background-color: #6FF;
height: 10px;
width: 100px;
position: absolute;
left: 0;
top: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="slider"></div>
<div id="red" class="item"></div>
<div id="blue" class="item"></div>
<div id="yellow" class="item"></div>
<div id="green" class="item"></div>
Update 2:
For Deining The Start Position You Should Replace This Part:
$("#slider").animate({
"left": $(".item:first").position().left + "px",
"width": $(".item:first").width() + "px"
}, 0);
With This:
$("#slider").animate({
"left": $("#TAG_ID").position().left + "px",
"width": $("#TAG_ID").width() + "px"
}, 0);
NOTE TAG_ID is your starting div id property
Update 3:
In case that user didn't select a tab:
$("#slider").delay(3000).animate({
"left": $(this).position().left + "px",
"width": $(this).width() + "px"
}, 500);

Categories

Resources