Randomize a div position - javascript

I've made a program where you press a button and a div positions itself randomly.
function Init()
{
div = document.getElementById("pixel");
spaceW = screen.height - div.height;
spaceH = screen.width - div.width;
setInterval(moveIt, 1000);
}
function moveIt()
{
div.style.top = (100*Math.random()) + "%";
div.style.left = (100*Math.random()) + "%";
}
The thing is, it only works when I use the setInterval. I only want the div to move ONCE. I'll erase the setInterval, and then what?

If you look through the documentation, you will see setInterval() fires at specific and regular intervals. If you want to only fire your function ONCE, use setTimeout() instead:
function Init()
{
div = document.getElementById("pixel");
spaceW = screen.height - div.height;
spaceH = screen.width - div.width;
setTimeout(moveIt, 1000);
}
function moveIt()
{
div.style.top = (100*Math.random()) + "%";
div.style.left = (100*Math.random()) + "%";
}
Init();
#pixel
{
width: 50px;
height: 50px;
background-color: red;
position: absolute;
}
<div id="pixel"></div>

SetInterval repeats every given interval
setTimeout runs once when the timeout expires
Sounds like you need to use setTimeout if you'd like it run once
function sayHi() {
alert('Hello');
}
setTimeout(sayHi, 1000)
see fiddle not created by me

If it works this way then declare a variable for the setInterval() then you can distroy that interval in the other function, like this varible.clearInterval()
some=setInterval(moveIt,200);//this one in caller function.
some.clearInteraval();//here this statment should be in moveIt
here you should declare some as global variable

Related

how to refresh two functions without reloading the page in html

i need to refresh the blockrandompos and animblock without refreshing the page
var player = document.getElementById("player");
var block = document.getElementById("block");
function goleft(argument) {
player.classList.add("animatel");
setTimeout(function() {
player.classList.remove("animatel");
}, 1);
console.log("left");
}
function goright(argument) {
player.classList.add("animater");
console.log("right");
}
function blockrandompos(argument) {
var block3 = document.getElementById("block");
var posleftblock = Math.floor(Math.random() * 370) + 1; //random numbers from 200 to 300 pos
var info = block3.setAttribute("style", "width:30px; height:30px; position: relative; left:" + posleftblock + "px;"); //block settings
console.log(posleftblock);
}
function animblock(argument) {
block.classList.add("animationblock");
console.log(block.classList);
}
blockrandompos()
animblock()
You are probably looking for an event and subsequently an event-listener that can call a function when the event takes place. Beyond onLoad and onClick, there are a crazy amount of events that you can use.
https://developer.mozilla.org/en-US/docs/Web/Events
So the question is, when do you want to run your functions exactly? Maybe we can help tell you which event to use.

Animate background image javascript not working

I want to achieve a background animate image, that moves from right to left, but the image won´t animate, could you help me verify my code?
<body>
<div id="background-container"></div>
<script> type="text/javascipt">
function animateBackground(elem, speed) {
var x = 0 ;
var y = -50;
elem.style.backgroundPosition = x + 'px' + ' ' + y + 'px';
var timer = setInterval (function(speed) {
elem.style.backgroundPosition = x + 'px' + ' ' + y + 'px';
x--;
if (x == -600) {
clearInterval(timer);
}
},speed)
}
document.addEventListener("DOMContentLoaded", animateBackground(document.getElementById('background-container'), 15), false);
</script>
</body>
Your code is quite ugly but actually it looks fine. What is definitely wrong is how you are adding the event handler. Instead of adding a handler function, you call your handler function inline, so it actually doesn't add any listener. You should pass the function itself, for example like this, using an anonymous function inline.
document.addEventListener("DOMContentLoaded", function() { animateBackground(document.getElementById('background-container'), 15); }, false);
You could have provided a jsfiddle link, which would have made it easy. By the way here is the working jsfiddle, https://jsfiddle.net/pmankar/4o88z0tt/
I added a css background to the div tag using
div{
background-image: url("https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png");
height: 100px;
width: 600px;
border: 2px solid green;
}
Rest assured, I didn't do any changes to your js code or the html code. It worked fine for me.

How to get width from animated div in jQuery

Thanks in advance for your support here. I have a simple code here but I wonder why it doesn't work.
This code below was put into a variable "percent"
var percent = $('#div').animate({width:80 + '%'},1000);
and I want to use the variable to become a text or content to a specific div. I tried to do it this way, however it doesn't work.
$('#val').text(percent); or $('#val').html(percent);
I tried to use the parseInt() function from JavaScript, but it doesn't work as well.
$('#web-design').text(parseInt(percent));
Do you have any suggestions or is this possible?
I am not sure if the line code it is correct
var percent = $('#div').animate({width:80 + '%'},1000);
To find the with property for #div I will do something like this
$('#val').text($("#div").css("width"))
or
$('#val').text($("#div").width())
The animate function does not return the changes to the element. To get the width you will have to use .width() but you will get it in pixel and not percentage.
var width = $('#div').width();
You can try this code:
$('#div1').animate({width:80 + '%'},{
duration:1000,
easing:'swing',
step: function() { // called on every step
$('#div1').text(Math.ceil($('#div1').width()/$('#div1').parent().width()*100) + "%");
}
});
This will print the Div-Width % as text in Div at every step of update.
You code is going to animate to 80% width in 1 second (1000 ms). You can increase the percentage width by 1% each iteration and update your #val at the same time until you hit 80. Below is the example based on 10000ms (10 secs), you can change the starting parameters such as duration, endWidth, startWidth to suit.
Demo: http://jsfiddle.net/zthaucda/
HTML:
<div class="my-anim-div"></div>
<button class="start-animating">Start animation</button>
<div id="val">Width will display here</div>
CSS:
.my-anim-div {
width:0%;
height:200px;
background-color:red;
}
Javascript including jQuery library:
var duration = 10000;
var endWidth = 80;
var startWidth = 0;
$('.start-animating').on('click', function () {
// work out the interval to make the animation in `duration`
var interval = duration / (endWidth - startWidth);
console.log(interval);
var myInterval = setInterval(function () {
// Increment the startWidth and update the width of the div and the display
startWidth++
// update div width
$('.my-anim-div').animate({
'width': startWidth + '%'
}, interval);
// update display
$('#val').text(startWidth + '%');
if (startWidth == 80) {
// then exit the interval
clearInterval(myInterval);
}
}, interval);
});
If you mean you want to get the current width of the div you can use clientWidth property:
$('#div')[0].clientWidth

Not sure why this isn't working - Javascript basic increment function

I am writing code to increment the most basic progress bar ever...... it just isn't working.
These are the variable used:
map.progress_bar = // the progress div that grows inside a container div that is the width of the screen (100%);
progress = 0;
state.window_width = // the width of the window or otherwise $(window).width();
setTimeout(function incProgress(){
if ( map.progress_bar.width() < state.window_width ) {
progress += 10;
map.progress_bar.css({
width: String(progress + '%')
});
console.log('progress: ', map.progress_bar.width());
console.log('window: ', state.window_width);
setTimeout(incProgress(), 300);
}
}, 300);
Please do not ask me to do setInterval. Please explain to me why on earth this does not work, I feel very unhappy.
setTimeout(incProgress(), 300);
You are calling the function and passing its return value (undefined) to setTimeout.
You need to pass a function to setTimeout.
Remove the ().

Change DIV margin on interval

I am trying to change the margin of each element, using setAttribute.
How can I able to use my variable dist "distance" to decrease value until 10, every after delay "interval"?
var dist=200; var speed = 2000;
function slideLeft(x){
dist--;
slideSet[x].setAttribute("style","margin-right:"+dist+"px;");
setTimeout(slideLeft(x), delay);
}
Take these style and elements for example...
.widiv { margin-right:200px; }
<div>
<div class="widiv" ></div>
<div class="widiv" ></div>
</div>
Thanks a lot.
Here's your code with some changes: See fiddle http://jsfiddle.net/chrismoutray/4p3xX/
var dist = 200, delay = 500,
slideSet = document.getElementsByTagName('div');
function slideLeft(x) {
dist--;
if (dist < 0) return;
slideSet[x].setAttribute("style", "margin-right:" + dist + "px;");
setTimeout(function() {
slideLeft(x);
}, delay);
}
slideLeft(1);
With a few additions to the styling:
.widiv {
margin-right:200px;
float:left;
width: 100px;
border: 1px solid black;
height: 100px; }
The main differences are that when calling setTimeout I'm using a function delegate (function() { <your code here> }) to call the slideLeft method so that x variable is used correctly - I don't think you can pass a statement into setTimeout without doing it this way.
Also in styling the divs I made sure to include a float left other wise the change to margin right doesn't make sense - should this be margin left instead?

Categories

Resources