Rotating DIV spins slowly on second click - javascript

I think I overlooked something. This is a very simple spin-the-bottle game.
Javascript/jQuery
$('.bottle').on('click', function(e) {
this.removeAttribute('style');
var deg = 3000 + Math.round(Math.random() * 500);
var css = '-webkit-transform: rotate(' + deg + 'deg);';
this.setAttribute(
'style', css
);
});
CSS:
.bottle {
width: 200px;
height: 200px;
background-image: url(img/bottle.png);
-webkit-transition: -webkit-transform 6s ease-out;
}
HTML:
<div class="bottle"></div>
This works perfectly on the first click of the bottle. But starting from the second click, the spin is very very slow?

Try this : http://jsfiddle.net/sMcAN/
var i = 1;
$('.bottle').on('click', function(e) {
this.removeAttribute('style');
var deg = 3000 + Math.round(Math.random() * 500);
deg = ((-1) ^ i) * deg;
var css = '-webkit-transform: rotate(' + deg + 'deg);';
this.setAttribute('style', css);
i++;
});​
Another update : http://jsfiddle.net/sMcAN/2/

This is because at first, you are going from 0 to a value over 3000. But then, the value is always within 3000 - so the difference is not big enough and it still takes the 6 seconds you have defined.
One solution would be to make sure that you offset the value and make it different by few thousand each time.
var i = 0, offset = [2000, 4000, 6000, 3000, 5000, 1000];
$('.bottle').on('click', function(e) {
this.removeAttribute('style');
var deg = offset[i] + Math.round(Math.random() * 500);
i++;
if (i > 5) {
i = 0;
}
var css = '-webkit-transform: rotate(' + deg + 'deg);';
this.setAttribute(
'style', css
);
});​

math.round(math.random() * 1000);
Try that

Related

How do I call a function every whatever seconds in Javascript?

Not sure why this is so hard to do in Javascript... Slightly frustrating LOL
Here's one of the ways I've tried to do it:
function rotateDavid() {
$("#david").css({
'transform' : 'rotate(90deg)'
});
setTimeout(rotateDavid, 10000);
};
rotateDavid();
It will do it once but doesn't repeat... I dunno...
The problem here is not how you are calling the function. This way is actually preferred over setInterval in some cases.
The issue you have is that setting the Css to 90degrees is not changing it over and over. You are setting it to the same degree value every time.
You need to update the angle on every iteration. So in this case you want to add 90 to it.
var rotation = 0;
function rotateDavid() {
rotation += 1
$("#david").css({
'transform' : 'rotate(' + (90 * rotation) + 'deg)'
});
setTimeout(rotateDavid, 1000);
};
rotateDavid();
div{
width:100px;
height: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="david">Hi</div>
You can also use a mod operator to keep the number from getting huge.
'transform' : 'rotate(' + (90 * (rotation%4)) + 'deg)'
Your method, actually, is called every 10s. You can check it if you add a log to the console inside the method. However, you was setting the css property always to the same value, so you won't see any visual effect. A possible fix is shown on next example:
function rotateDavid(rot)
{
$("#david").css({
'transform': `rotate(${rot}deg)`
});
rot = rot + 90 >= 360 ? 0 : rot + 90;
setTimeout(() => rotateDavid(rot), 5000);
};
rotateDavid(0);
#david {
background: skyblue;
width: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="david">David</div>
Even more, you can get similar functionality using setInterval():
function rotateDavid(rot)
{
$("#david").css({
'transform': `rotate(${rot}deg)`
});
};
var rot = 90;
setInterval(
() => {rotateDavid(rot); rot = rot + 90 >= 360 ? 0 : rot + 90;},
5000
);
#david {
background: skyblue;
width: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="david">David</div>

Plain JavaScript rotate

I would like to rotate an object exactly as the fiddle: http://jsfiddle.net/nqC6T/
however, I do not have the JQuery library available in my project.
var angle = 0;
$(document).ready(function () {
$('#rotate').click(function () {
angle += 90;
$('#div1').animate({ rotate: angle }, {
step: function (now, fx) {
$(this).css('-webkit-transform', 'rotate(' + now + 'deg)');
$(this).css('-moz-transform', 'rotate(' + now + 'deg)');
$(this).css('transform', 'rotate(' + now + 'deg)');
},
duration: 3000
}, 'linear');
});
});
Would this be possible in plain JavaScript?
Thanks!
A plain Javascript based solution is as follows:
var obj = document.getElementById("div1");
var total = 100;
var current = 0;
setInterval(function(){
if (current < total) {
current += 1;
obj.style.transform = 'rotate('+current+'deg)';
}
}, 1);
This is just an example. You can definitely improve this code further. As mentioned by Mohammad, you can also use CSS3 based animations.
You could add a 'rate of speed' and 'initial rotate position' to the element you
wish to rotate, by simply using a closure to automatically return a given rotational increase/decrease rate:
var division=document.getElementById("rotdiv");
function rotElem(startpos,rate){
return function(mult){
return division.style="transform:rotate("+ startpos+ mult*rate++ +"deg)";};
}
var rotelem = rotElem(0,1);
var atspeedof = setInterval(rotelem.bind(null),1000,10);
rotElem(0,1) You define optional start position '0' of the element before starting rotate and the self-increasing 'unit' of change return by the closure.
setInterval(rotelem.bind(null),1000,10) You call setInterval to run the closure at each second AND passing the value '10' as the multiplier for the rate speed. Changing the rightmost argument after the setInterval time, increases or decreases rotation.
var division = document.getElementById("rotdiv");
function rotElem(startpos, rate) {
return function(mult) {
return division.style = "transform:rotate(" + startpos + mult * rate++ + "deg)";
};
}
var rotelem = rotElem(0, 1);
var atspeedof = setInterval(rotelem.bind(null), 500, 10);
#rotdiv {
position: relative;
margin: auto;
top: 50px;
width: 80px;
height: 80px;
background-color: gray;
}
<div id='rotdiv'>
</div>

How can I make my div spawn within 400 px of either side using jquery?

I'm making an animated background for a webpage that spawn div elements to look like bubbles and animates their transparency. I want the bubbles to only spawn within the left 400px and the right 400px of the screen. I can get them to spawn in the middle, but when I try to make it spawn on the edges it breaks the code. (maybe an infinite loop?)
function bubble() {
var rightOffset = $(window).width() - 400; //where i want them on the right
do {
var leftPx = Math.floor(Math.random() * $(window).width() - 100);
} while (leftPx >= 400 || rightOffset <= leftPx);
var topPx = Math.floor(Math.random() * $(window).height() - 100); //not even going to worry about the top yet
if(bubbleCount <= 30){
bubbleCount ++;
$('html').append("<div class=bubble style=' left: " + leftPx + "px; top: " + topPx + "px;'></div>");
$('.bubble').animate({
opacity: 0.5,
}, 3000, 'swing')
.animate({
opacity: 0,
}, 3000, 'swing', function(){
$(this).remove();
bubbleCount -= 1;
});
}
}
Why not simply randomize the side as well? This way you don't have to check and discard potential positions. Something like this.
function randomBetween(min,max) {
return Math.floor(Math.random()*(max-min+1)+min);
}
var width = $(window).width();
var leftPixels = Math.round(Math.random()) ? randomBetween(0, 400) :
randomBetween(width - 400, width);
What happens here is that it first randomly generates 0 or 1, and then if it's 1 it generates a LEFT side value and if 0 generates a RIGHT side value. No extra iterations that slow down your program.
I reproduced your bubble effect and didn't end up with a break in code!
I think what you are missing is that for an absolute-positioned bubble to be positioned from right, you need to give it a right CSS offset value; likewise, for a left absolute-positioned bubble, stick to the left property:
var rightOffset = $(window).width() - 400; //where i want them on the right
do {
var rightPx = Math.floor(Math.random() * $(window).width() - 100);
} while (rightPx >= 400 || rightOffset <= rightPx);
/*
* ...
*/
$('html').append("<div class='bubble' style=' right: " + rightPx + "px; top: " + topPx + "px;'></div>");

Create Random Falling Object in Jquery

I trying to make the div fall from top to bottom.
Here is the code that i tried but it doesn't satisfy my needs .I want to generate the 20 div once ready then how to make that 20 div falling continuously from top to bottom consistently. Is it possible to do that in jquery.
http://jsfiddle.net/MzVFA/
Here is the code
function fallingSnow() {
var snowflake = $('<div class="snowflakes"></div>');
$('#snowZone').prepend(snowflake);
snowX = Math.floor(Math.random() * $('#site').width());
snowSpd = Math.floor(Math.random() + 5000);
snowflake.css({'left':snowX+'px'});
snowflake.animate({
top: "500px",
opacity : "0",
}, snowSpd, function(){
$(this).remove();
fallingSnow();
});
}
var timer = Math.floor(Math.random() +1000);
window.setInterval(function(){
fallingSnow();
}, timer);
Much Appreciate your Help.
Thanks
Not sure if this is what you want.
I am animating 20 snowflakes, wait until animation finishes for all of them, then restart all over again.
jsfiddle
function fallingSnow() {
var $snowflakes = $(), qt = 20;
for (var i = 0; i < qt; ++i) {
var $snowflake = $('<div class="snowflakes"></div>');
$snowflake.css({
'left': (Math.random() * $('#site').width()) + 'px',
'top': (- Math.random() * $('#site').height()) + 'px'
});
// add this snowflake to the set of snowflakes
$snowflakes = $snowflakes.add($snowflake);
}
$('#snowZone').prepend($snowflakes);
$snowflakes.animate({
top: "500px",
opacity : "0",
}, Math.random() + 5000, function(){
$(this).remove();
// run again when all 20 snowflakes hit the floor
if (--qt < 1) {
fallingSnow();
}
});
}
fallingSnow();
Update
This version creates 20 divs only once, and animate them again and again.
jsFiddle
function fallingSnow() {
var $snowflakes = $(),
createSnowflakes = function () {
var qt = 20;
for (var i = 0; i < qt; ++i) {
var $snowflake = $('<div class="snowflakes"></div>');
$snowflake.css({
'left': (Math.random() * $('#site').width()) + 'px',
'top': (- Math.random() * $('#site').height()) + 'px'
});
// add this snowflake to the set of snowflakes
$snowflakes = $snowflakes.add($snowflake);
}
$('#snowZone').prepend($snowflakes);
},
runSnowStorm = function() {
$snowflakes.each(function() {
var singleAnimation = function($flake) {
$flake.animate({
top: "500px",
opacity : "0",
}, Math.random() + 5000, function(){
// this particular snow flake has finished, restart again
$flake.css({
'top': (- Math.random() * $('#site').height()) + 'px',
'opacity': 1
});
singleAnimation($flake);
});
};
singleAnimation($(this));
});
};
createSnowflakes();
runSnowStorm();
}
fallingSnow();
Update2
This one that initializes the left once the animation is done for each snowflake, looks more natural in my opinion.
Also changed the delay from
Math.random() + 5000
to
Math.random()*-2500 + 5000
demo
This is simple.
Your design of function must be this.
function snowflake()
{
if($(".snowflakes").length <= 20)
{
generate_random_snowflake();
}
else
{
call_random_snowflake();
}
}
check this out, pretty simple i just added a function that triggers jquerysnow() and then calls itself again wit random time
updated code now it will just create 20 snow flakes
snowCount = 0;
function snowFlakes(){
console.log(snowCount);
if(snowCount > 20){
return false
}else{
var randomTime = Math.floor(Math.random() * (500) * 2);
setTimeout(function(){
snowCount = snowCount +1;
jquerysnow();
snowFlakes();
},randomTime);
}
}
function jquerysnow() {
var snow = $('<div class="snow"></div>');
$('#snowflakes').prepend(snow);
snowX = Math.floor(Math.random() * $('#snowflakes').width());
snowSpd = Math.floor(Math.random() * (500) * 20);
snow.css({'left':snowX+'px'});
snow.html('*');
snow.animate({
top: "500px",
opacity : "0",
}, 2000, function(){
$(this).remove();
//jquerysnow();
});
}
snowFlakes()
http://jsfiddle.net/v7LWx/22/

Adapt random image placement code for flexible layout

I'm looking for an effect very similar to this:
http://jsfiddle.net/G5Xrz/
function rnd(max) { return Math.floor(Math.random()*(max+1)) }
function showImage(container, maxwidth, maxheight, imgsrc, imgwidth, imgheight) {
var id = "newimage" + rnd(1000000);
$(container).append(
"<img id='" + id + "' src='" + imgsrc +
"' style='display:block; float:left; position:absolute;" +
"left:" + rnd(maxwidth - imgwidth) + "px;" +
"top:" + rnd(maxheight - imgheight) + "px'>");
$('#' + id).fadeIn();
return id;
}
setInterval(
function() {
showImage("#container", 400, 600,
"http://placekitten.com/" + (90 + rnd(10)) + "/" + (90 + rnd(10)),
100, 100);
}, 700);
But i'd prefer a flexible layout, ie images not bound by a div with predefined height and width, instead responding to the dimensions of the browser.
The following piece of code seems to have a more appropriate way of generating the random positions:
http://jsfiddle.net/Xw29r/15/
function makeNewPosition(){
// Get viewport dimensions (remove the dimension of the div)
var h = $(window).height() - 50;
var w = $(window).width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh,nw];
}
function animateDiv(){
var newq = makeNewPosition();
var oldq = $('.a').offset();
var speed = calcSpeed([oldq.top, oldq.left], newq);
$('.a').animate({ top: newq[0], left: newq[1] }, speed, function(){
animateDiv();
});
};
However I'm very much a beginner with javascript and I don't know how to combine the two.
Can anyone help?
Thanks
Take this part from the second code:
// Get viewport dimensions (remove the dimension of the div)
var h = $(window).height() - 50;
var w = $(window).width() - 50;
and use those variables h and w with the browser height and width (minus 50) as the appropriate parameters in this part of the first code:
setInterval(
function() {
showImage("#container", 400, 600,
"http://placekitten.com/" + (90 + rnd(10)) + "/" + (90 + rnd(10)),
100, 100);
}, 700);
Also, the first code has this HTML:
<div id="container" style="width:400px; height:600px; background: green; position:relative"></div>
That hard-codes the height and width at pixel values. You can use a CSS percentage value to make the width respond to the parent container's size. However, you will need JS to set the height properly; a percentage for the height does nothing
Putting that all together (and removing the "minus 50" part), you get this:
jsFiddle demo
<div id="container" style="width:100%; height:100px; background: green; position:relative"></div>
function adjustContainerHeight(height) {
$('#container').height(height);
}
adjustContainerHeight($(window).height());
setInterval(
function() {
var h = $(window).height();
var w = $(window).width();
adjustContainerHeight(h);
showImage("#container", w, h,
"http://placekitten.com/" + (90 + rnd(10)) + "/" + (90 + rnd(10)),
100, 100);
}, 700);
This updates the height of the container when the page is first loaded, and once again whenever the random image is placed. More robust code would have a separate height-adjusting event handler that updates the height whenever the page size changes.

Categories