I want to change the position of div with for loop ..
I made an animation .. When i click a div ( circle ) it moves to a position that is being determined with Math.random() ..
I dont want to click the div to move to another position .
I want to use for loop method and i want div to move another position in every 2 seconds or some seconds ..
Do you have any advise .. Thanks
Click to see how it is
$(document).ready(function () {
$("#circle").click(function () {
var width = Math.random();
var yeniwidth = width * 500;
margin = Math.round(yeniwidth);
$("#circle").css("margin-top", margin + "px");
var height = Math.random();
var yeniheight = height * 1000;
margin2 = Math.round(yeniheight);
$("#circle").css("margin-left", margin2 + "px");
});
});
Codepen
You don't really need a for-loop to do that. Instead of executing the code after clicking the div, you could just use the setInterval function instead:
$(document).ready(function () {
window.setInterval(function(){
var width = Math.random();
var yeniwidth = width * 500;
margin = Math.round(yeniwidth);
$("#circle").css("margin-top", margin + "px");
var height = Math.random();
var yeniheight = height * 1000;
margin2 = Math.round(yeniheight);
$("#circle").css("margin-left", margin2 + "px");
}, 5000);
});
Just change the number 5000 to adjust the time that should pass before the code is executed again (1000ms is 1 second).
On Codepen
Related
How can I change an element with a fixed width in px when i resize the window? I need to use an absolute unit, i can not use relative units like % or vw.Every time the window is resized with 1 px i need to decrease the element width by 0.2px.
I tried to use the window resize eventListener but i don't know what calculations needs to be done.
What you want can be achieved by using javascript. I've created a logic to do that :
<script>
function myFunction() {
var initialscreenwidth = window.innerWidth; //Set Initial Screen Width
setInterval(function() { //looping the script
var screenwidth = window.innerWidth;
var difference = initialscreenwidth - screenwidth; //Calculating the change in screen-size
if (difference != 0) { //Checking if there is a change in width
var element = document.getElementById('demo');
var style = window.getComputedStyle(element, null).getPropertyValue('font-size'); //Getting default font-size of the element
var initialfontsize = parseFloat(style);
var fontdifference = -(parseFloat(difference) / 5); //1px change in screen-size = 0.2px change in font-size
var newfontsize = initialfontsize + fontdifference;
var newfontsizepx = newfontsize + "px";
if (newfontsize > 1) {
document.getElementById("demo").style.fontSize = newfontsizepx;
}
}
initialscreenwidth = window.innerWidth;
}, 300); //reloads in every 300ms
}
myFunction();
</script>
Paste this at the end of your body section, somehow using this in the head section is not working.
I wish to create a div and position it in random places on the screen every 2 seconds. How would I accomplish this using PHP or Javascript? I am ok with using things like CSS.
div:
var blueMass = document.createElement('div');
blueMass.style.position = "absolute";
blueMass.innerHTML = "<img src='./pic/bluemass.png' height='35' width='35' />";
blueMass.id = "bluemass";
blueMass.className = "bluemass";
// my timer
window.setInterval(function(){
// Create the divs in here
}, 3000);
<div class="bluemass" id="bluemass">
<img src='./pic/bluemass.png' height='35' width='35' />
</div>
// no jQuery
$=document.querySelector.bind(document); // create selector
setInterval(function(){
s=$('div').style;
s.top=Math.random()*window.innerWidth+'px'; // multiply random (0..1) value by window height (you may want to subtract div height)
s.left=Math.random()*window.innerHeight+'px'; // ... height ...
},2000)
div{position:fixed}
<div>div</div>
// with jQuery
setInterval(function () {
$('#mydiv').css({
top: Math.random() * ($(window).height() - $('#mydiv').height()) + 'px', // multiply random .width(0..1) value by window height minus div height
left: Math.random() * ($(window).width() - $('#mydiv').width()) + 'px'
})
}, 2000)
#mydiv{position:fixed}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mydiv">div</div>
Just get width and height of document and use that to generate random number. You already have created the element in html, so no need to redo all that in JS.
In your specs you wanted every 2 seconds, so that would be 2000 ms in your timer.
In your timer function you would simply add the left and top of element with the new random numbers.
var blueMassElement = document.getElementById('bluemass');
var currentTop = 0;
var documentHeight = document.documentElement.clientHeight;
var documentWidth = document.documentElement.clientWidth;
window.setInterval(function() {
// Create the divs in here
currentTop = Math.floor(Math.random() * documentHeight) + 1;
currentLeft = Math.floor(Math.random() * documentWidth) + 1;
blueMassElement.style.top = currentTop + "px";
blueMassElement.style.left = currentLeft + "px";
}, 2000);
#bluemass {
position:absolute;
}
<div id="bluemass" class="bluemass">
<img height="35" width="35" src='http://vignette4.wikia.nocookie.net/mrmen/images/5/52/Small.gif/revision/latest?cb=20100731114437' />
</div>
I have created a script that animates the height of an element in 500ms.
The timer works fine but I am struggling to make the height increase consistently.
How do I animate the height smoothly within the time period? It jumps at the moment.
I want to replace the following with something smarter:
self.startHeight + 5
I imagine it has something to do with the speed and elapsed time?
https://jsfiddle.net/zrm7xena/1/
(function () {
'use strict';
var animator = {};
animator.endHeight = 200; //The end height
animator.interval = null; //Create a variable to hold our interval
animator.speed = 500; //500ms
animator.startHeight = 0; //The start height
animator.animate = function (el) {
var self = this,
startTime = Date.now(); //Get the start time
this.interval = setInterval(function () {
var elapsed = Date.now() - startTime, //Work out the elapsed time
maxHeight = self.maxHeight; //Cache the max height
//If the elapsed time is less than the speed (500ms)
if (elapsed < self.speed) {
console.log('Still in the timeframe');
//If the client height is less than the max height (200px)
if (el.clientHeight < self.endHeight) {
self.startHeight = self.startHeight + 5; //Adjust the height
el.style.height = self.startHeight + 'px'; //Animate the height
}
} else {
console.log('Stop and clear the interval');
el.style.height = self.endHeight + 'px';
clearInterval(self.interval);
}
}, 16); //60FPS
};
animator.animate(document.getElementById('box'));
}());
Thanks in advance!
Carorus gave a great answer below. I have updated my jsfiddle so you can see the final code working:
https://jsfiddle.net/zrm7xena/8/
Typhoon posted a great link in relation to the browser FPS:
How to determine the best "framerate" (setInterval delay) to use in a JavaScript animation loop?
I would probably use request animation frame instead of a setInterval:
http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
Cheers all!
The harcoded 5 that you are using for the height increment doesn't allow the animation to complete the entire final height (200) in the time that you are setting (500ms), you need to calculate the height increment based on the final height, the animation time and the interval to make it consistent:
(function () {
'use strict';
var animator = {};
animator.endHeight = 200; //The end height
animator.interval = null; //Create a variable to hold our interval
animator.speed = 500; //500ms
animator.startHeight = 0; //The start height
animator.interval = 16;
animator.animate = function (el) {
var self = this,
startTime = Date.now(); //Get the start time
//calculating height variation
self.deltaHeight = (animator.endHeight / animator.speed) * animator.interval;
this.intervalId = setInterval(function () {
var elapsed = Date.now() - startTime, //Work out the elapsed time
maxHeight = self.maxHeight; //Cache the max height
//If the elapsed time is less than the speed (500ms)
if (elapsed < self.speed) {
console.log('Still in the timeframe');
//If the client height is less than the max height (200px)
if (el.clientHeight < self.endHeight) {
self.startHeight = self.startHeight + self.deltaHeight; //Adjust the height
el.style.height = self.startHeight + 'px'; //Animate the height
}
} else {
console.log('Stop and clear the interval');
el.style.height = self.endHeight + 'px';
clearInterval(self.intervalId);
}
}, animator.interval); //60FPS
};
animator.animate(document.getElementById('box'));
}());
I am trying to make this function works only when the screen size is above 1024px.
//Parallax background image
var velocity = 0.5;
function update(){
var pos = $(window).scrollTop();
$('.parallax').each(function() {
var $element = $(this);
var height = $element.height();
$(this).css('background-position', '40%' + Math.round((height - pos) * velocity) + 'px');
});
};$(window).bind('scroll', update); update();
Here is what I have tried to do:
//Parallax background image
var velocity = 0.5;
$(window).on("ready resize", function() {
if ($(window).width() < 770) {
function update(){
var pos = $(window).scrollTop();
$('.parallax').each(function() {
var $element = $(this);
var height = $element.height();
$(this).css('background-position', '40%' + Math.round((height - pos) * velocity) + 'px');
});
};});$(window).bind('scroll', update); update();
I really don't know what I am doing wrong...
You haven't stated what the problem you're coming across is. If it's "my code doesn't work", then perhaps you should check your syntax first. Your braces are messed up.
//Initialize velocity and empty update function
var velocity = 0.5;
var update = function () {};
//When window is ready (content loaded) OR resized, execute the following function
$(window).on("ready resize", function () {
if ($(window).width() >= 1024) { //Check if window width is 1024px wide or larger
update = function () { //Set update to run this function when executed.
var pos = $(window).scrollTop(); //Get scrollbar position https://api.jquery.com/scrollTop/
//For each element with 'parallax' class, execute the following function
$('.parallax').each(function () {
var $element = $(this); //Get the current parallax-classed element
var height = $element.height(); //Save the current height of this element
//Set the CSS of this parallax-classed element set the background position
$(this).css('background-position', '40% + ' + Math.round((height - pos) * velocity) + 'px');
});
};
} else { //Execute if screen width is < 1024px
update = function () {}; //Set update to do nothing
}
});
//When window is scrolled through, run the update function
$(window).bind('scroll', update);
//update();
Last line is unnecessary, as resize will handle function value, and scroll will handle the execution.
You were missing a + or - within the background-position setting.
So for example, if the result of your Math.round() was "30", then Javascript would interpret that line as $(this).css('background-position', '40%30px'); which obviously would cause issues. I'm sure you wanted it to say something like $(this).css('background-position', '40% + 30px');.
I have a picture of an Air balloon. I need it to fly around my page randomly (it is kind of small). I need it only to fly in the top half of my page. I found the following code:
$("#Friends").animate({
top: "-=30px",
}, duration );
But I'm not sure how I could loop it and have it go both on the x axis and the y axis. Thanks if you can! I do have jQuery enabled :)
How about something like this.... LIVE FIDDLE
HTML
<img src="http://www.birdsnways.com/imgs/blbd48rt.gif" id="picture" />
CSS
#picture{
position:absolute;
}
JS
doNextPoint();
function doNextPoint(){
var maxX = $(window).width() - $('#picture').width();
var newX = rand(0, maxX);
var maxY = ($(window).height()/2) - $('#picture').height();
var newY = rand(0, maxY);
var speed = rand (1000, 3000);
$('#picture').animate({
'top': newY + 'px',
'left': newX + 'px'
}, speed, function(){
doNextPoint();
});
}
function rand (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
CSS
#friends { position: absolute; }
Markup
<img src="http://jsfiddle.net/img/logo.png"
id="friends"/>
JS
function moveit() {
var newTop = Math.floor(Math.random()*350);
var newLeft = Math.floor(Math.random()*1024);
var newDuration = Math.floor(Math.random()*5000);
$('#friends').animate({
top: newTop,
left: newLeft,
}, newDuration, function() {
moveit();
});
}
$(document).ready(function() {
moveit();
});
Live demo:
http://jsfiddle.net/W69s6/embedded/result/
More updated Live Demo: http://jsfiddle.net/9cN4C/
(old demo is obsolete and has a broken link, however the code is still correct so it is left for reference, not for demonstration)
You can stick that code into a named function, and then add that function as the callback parameter for the animation, so it will call itself again after it finishes.
var flying;
flying = function() {
$("#Friends").animate({
top: "-=30px", // you'll need to change this
},
duration,
flying
);
}
flying();
As is, it will just keep flying upward because the animation is always set to go up by 30 px. You'll have to change the flying function to randomize the motions a bit. For more realism, save the previous movement, and just change it by a little (small acceleration) so it doesn't have very jerky motions.
To loop it: use SetTimeout: https://developer.mozilla.org/en/window.setTimeout
For the x-axis, use the CSS property left: (top: will get you y-axis)