I tried to change div width every 1 second by 5px using JavaScript. How can I make this work?
Here's my code:
<html>
<head>
<title>JS Functions</title>
</head>
<body>
<div style="width:100px; height:100px; background:gray" id="box" onclick="bigger()"></div>
<script>
function bigger()
{
var w = 100
var h = 100
while(w < 1000, h < 1000)
{
w = w+5;
h = h+5;
document.getElementById('box').style.width = w
document.getElementById('box').style.height = h
setInterval();
}
}
</script>
</body>
</html>
No while loop needed. You can just use setInterval:
var w = 100;
var h = 100;
var foo = setInterval(function () {
if(w>1000) cancelInterval(foo)
w = w + 5;
h = h + 5;
document.getElementById('box').style.width = w + 'px';
document.getElementById('box').style.height = h + 'px';
}, 1000);
<div style="width:100px; height:100px; background:gray" id="box" onclick="bigger()"></div>
You need to use setInterval to call your code every second, so move it outside of the bigger() function. Also you need the full value for style, including the unit you're using.
try this
<html>
<head>
<title>JS Functions</title>
</head>
<body>
<div style="width:100px; height:100px; background:gray" id="box"></div>
<script>
var w = 100;
var h = 100;
function bigger()
{
if (w < 1000 && h < 1000)
{
w = w+5;
h = h+5;
document.getElementById('box').style.width = w + 'px';
document.getElementById('box').style.height = h + 'px';
} else {
clearInterval(int);
}
}
var int = setInterval(bigger, 1000);
</script>
</body>
</html>
Let's say you have a div wth id='boxToEnlarge'
The JSFiddle: http://jsfiddle.net/7qtb1u8e/1/
And this is the actual code:
function enlargeBox(){
//get current size
var currentWidth = document.getElementById('boxToEnlarge').offsetWidth;
var currentHeight = document.getElementById('boxToEnlarge').offsetHeight;
//add 5 more pixels to current size
document.getElementById('boxToEnlarge').style.width = currentWidth + 5 +'px';
document.getElementById('boxToEnlarge').style.height = currentHeight + 5 +'px';
}
//call the enlargeBox func every 1 sec (1000 milliseconds)
setInterval(function(){enlargeBox()},1000);
We are reading the current size of the div we want to enlarge then we add 5px to that amount and apply it on it's width/height CSS properties.
We wrap the above in a function and using setInterval, we call that function once every n milliseconds, in this case 1000ms which equals 1 second
Related
I have a moving image that moves across the screen from left to right. I need to replace it in the middle of the screen with another image for 5 seconds and then replace it back again resume the movement. could anyone please help me with that ?
Here's the code I have so far. I'm new to this , any help would be very much appreciated ! Thanks in advance !
const catImg = document.querySelector('img');
let marginLeft = (catImg.style.left = 0);
let marginRight = catImg.style.right;
const body = document.querySelector('body');
body.style.position = 'relative';
function catWalk() {
let halfWidth = window.innerWidth / 2 - catImg.width / 2;
marginLeft = '0px';
if (
parseInt(window.getComputedStyle(catImg).left) <
Math.floor(window.innerWidth / 2 - catImg.width / 2)
) {
marginLeft = parseInt(window.getComputedStyle(catImg).left) + 10 + 'px';
catImg.style.left = marginLeft;
return;
} else if (parseInt(window.getComputedStyle(catImg).left) == Math.round(halfWidth / 10) * 10) {
catImg.src = 'https://tenor.com/StFI.gif';
function dancingCat(timePassed) {
let startTime, endTime;
function start() {
startTime = performance.now();
return startTime;
}
function end() {
endTime = performance.now();
timePassed = endTime - startTime;
console.log(timePassed);
return endTime;
}
if (timePassed == 5000) {
catImg.src = 'http://www.anniemation.com/clip_art/images/cat-walk.gif';
}
}
} else if (
parseFloat(window.getComputedStyle(catImg).left) >
window.innerWidth - catImg.width / 2
) {
console.log('stop here');
catImg.style.left = '0px';
return;
}
return;
}
setInterval(catWalk, 50);
catWalk();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Cat Walk</title>
</head>
<body>
<img style="position: absolute;" src="http://www.anniemation.com/clip_art/images/cat-walk.gif" />
<script src="ex5-catWalk.js"></script>
</body>
</html>
Based on your code I made a refactor separating each sentence between functions. BTW, try to avoid declare functions within functions. I'm giving you just an example of how can you make it. I'm sure it could be better turning each function as pure, but it works fine.
Edition
Adding some lines to start function you can achieve a loop cycle when the cat overflows the right side window.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Cat Walk</title>
</head>
<body>
<img width="200" src="http://www.anniemation.com/clip_art/images/cat-walk.gif" />
<script type="text/javascript">
let interval, leftPos = 0, stopped = 0;
const img = document.querySelector('img');
const windowHalf = window.innerWidth / 2;
const middlePos = windowHalf - img.width / 2;
function step(img, size) {
leftPos += size;
return img.style.marginLeft = leftPos + 'px';
}
function start() {
interval = setInterval(() => {
if (leftPos < window.innerWidth) {
if (leftPos < middlePos || stopped) {
return step(img, 5);
} else {
clearInterval(interval);
return stop();
}
} else {
// restart variables when cat overflows window area
leftPos = 0;
stopped = 0;
}
}, 50)
}
function stop() {
img.src = 'https://tenor.com/StFI.gif';
stopped++
setTimeout(() => {
img.src = 'http://www.anniemation.com/clip_art/images/cat-walk.gif';
start()
}, 5000)
}
start();
</script>
</body>
</html>
I have created random stars using a js unction which manipulates CSS based on window height & width. My goal was to fit them at all-time in the viewport as I resize the height and width of the window.
The problem is every time that I resize the window, the js function adds CSS to previous ones without removing them first which causes a horizontal scroll and other unappealing visual issues.
Is there any way to prevent that? perhaps disabling and re-enabling the function or something else that fits the stars exactly in the viewport and make them behave dynamically as the width and height change without keeping the previous applied css properties and values?
<style>
body, html {margin: 0;}
#header {display: grid;background-color: #2e2e2e;width: 100vw;height: 100vh;overflow: hidden;}
#header i {position: absolute;border-radius: 100%;background: grey; }
</style>
<body>
<div id="header"></div>
<script>
window.onresize = function() {
skyCity();
};
function skyCity() {
for( var i=0; i < 400; i++) {
var header = document.getElementById("header"),
cityLight = document.createElement("i"),
x = Math.floor(Math.random() * window.innerWidth * .98),
y = Math.floor(Math.random() * window.innerHeight),
size = Math.random() * 1.5;
animate = Math.random() * 50;
cityLight.style.left = x + 'px';
cityLight.style.top = y + 'px';
cityLight.style.width = size + 1.5 + 'px';
cityLight.style.height = size + 1.5 + 'px';
cityLight.style.opacity = Math.random();
cityLight.style.animationDuration = 10 + animate + 's';
header.appendChild(cityLight);
}
};
skyCity();
</script>
</body>
Simply said, every time you resize, you call skyCity() which runs header.appendChild(cityLight); 400 times. It is just programmed to add new lights...
You can, a) remove every <i> from #header in skyCity() before the loop,
and b), b for better, init the 400 <i> once on load, on then on resize just update their properties.
it seems that the issue is it appends more i tags or stars when resizing, not really css issue.
I suggest to clear the wrapper #header before adding more <i>s.
You can do something like this:
window.onresize = function() {
skyCity();
};
function skyCity() {
var header = document.getElementById("header")
header.innerHTML=''
for( var i=0; i < 400; i++) {
var cityLight = document.createElement("i"),
x = Math.floor(Math.random() * window.innerWidth * .98),
y = Math.floor(Math.random() * window.innerHeight),
size = Math.random() * 1.5;
animate = Math.random() * 50;
cityLight.style.left = x + 'px';
cityLight.style.top = y + 'px';
cityLight.style.width = size + 1.5 + 'px';
cityLight.style.height = size + 1.5 + 'px';
cityLight.style.opacity = Math.random();
cityLight.style.animationDuration = 10 + animate + 's';
header.appendChild(cityLight);
}
};
skyCity();
#header {display: grid;background-color: #2e2e2e;width: 100vw;height: 100vh;overflow: hidden;}
#header i {position: absolute;border-radius: 100%;background: grey; }
<div id="header"></div>
You can check the full page link so you can try to resize the window
I would suggest you keep the "stars" as an array (cityLights in the code below) and apply the new style every time the browser size changes.
<style>
body, html {margin: 0;}
#header {display: grid;background-color: #2e2e2e;width: 100vw;height: 100vh;overflow: hidden;}
#header i {position: absolute;border-radius: 100%;background: grey; }
</style>
<body>
<div id="header"></div>
<script>
window.onresize = function() {
skyCity();
};
var header = document.getElementById("header");
var cityLights = []
for( var i=0; i < 400; i++) {
cityLights.push(document.createElement("i"));
}
function skyCity() {
for( var i=0; i < 400; i++) {
var cityLight = cityLights[i],
x = Math.floor(Math.random() * window.innerWidth * .98),
y = Math.floor(Math.random() * window.innerHeight),
size = Math.random() * 1.5;
animate = Math.random() * 50;
cityLight.style.left = x + 'px';
cityLight.style.top = y + 'px';
cityLight.style.width = size + 1.5 + 'px';
cityLight.style.height = size + 1.5 + 'px';
cityLight.style.opacity = Math.random();
cityLight.style.animationDuration = 10 + animate + 's';
header.appendChild(cityLight);
}
};
skyCity();
</script>
</body>
I have practiced one question and this is about checking time to click the shape that comes up. I want to save the the high score and compare with the next one coming up. It is just how to store the high score . It would be great help if somebody give the way to do it. Thank you in advance
<!doctype html>
<html>
<head>
<title> Javasript </title>
<style type="text/css">
#shape {
width: 200px;
height: 200px;
display:none;
position : relative;
}
</style>
</head>
<body>
<h1>Test your reaction </h1>
<p>Click on the boxes as soon as possible and win it </p>
<p>Your time taken <span id="timeTaken"></span></p>
<div id="shape"></div>
<script type="text/javascript">
var start = new Date().getTime();
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function makeShapeAppear() {
var top = Math.random() * 400 ;
var left = Math.random() * 400 ;
var width = (Math.random() * 200) + 100 ;
if (Math.random()> 0.5) {
document.getElementById("shape").style.borderRadius = "50%";
} else {
document.getElementById("shape").style.borderRadius = "0%"; }
document.getElementById("shape").style.backgroundColor = getRandomColor();
document.getElementById("shape").style.height = top + 'px';
document.getElementById("shape").style.width = width + 'px';
document.getElementById("shape").style.top = top + 'px';
document.getElementById("shape").style.left = left + 'px';
document.getElementById("shape").style.height = top + 'px';
document.getElementById("shape").style.display = 'block';
start = new Date().getTime();
}
function appearAfterDelay() {
setTimeout(makeShapeAppear, Math.random() * 2000 );
}
appearAfterDelay();
document.getElementById("shape").onclick = function() {
document.getElementById("shape").style.display = 'none';
var end = new Date().getTime();
var timeTaken = (end - start)/1000;
document.getElementById("timeTaken").innerHTML = timeTaken + "s";
appearAfterDelay();
}
</script>
</body>
</html>
I want to achieve something like image shown below.
More specifically, I need to have smiley faces randomly distributed throughout a 500px area and have a border on the right-hand side of the area.
but with the following code I am not getting the desired result.
<!DOCTYPE html>
<html>
<head>
<style>
img {
position: absolute
}
div {
width: 500px;
height: 500px
}
#rightSide {
position: absolute;
left: 500px;
border-left: 1px solid black
}
</style>
</head>
<body onload="generateFaces()">
<div id="leftSide"></div>
<div id="rightSide"></div>
<script>
var numberOfFaces = 5;
var top_position = 400;
var left_position = 400;
var theLeftSide = document.getElementById("leftSide");
var i = 0;
function generateFaces() {
while (i < numberOfFaces) {
var this_img = document.createElement("img");
this_img.src = "#";
this_img.style.top = top_position + "px";
this_img.style.left = left_position + "px";
theLeftSide.appendChild(this_img);
top_position = top_position - 50;
left_position = left_position - 50;
i++;
}
}
</script>
</body>
</html>
The result I am getting for the above code snippet looks like
How will I make it proper?
In your while loop you subtract 50 from top and left every time, so you get even distances for each image.
Use Math.random() for random values. The function returns values between 0 and 1, so multiply with the container size to get random positions.
You just need to go with random funtion if you require random positions. For fix position you need to implement particular position checks.
top_position = Math.random()*400; left_position = Math.random()*400;
JS Fiddle - https://jsfiddle.net/manishghec/13k8caen/
If you want to use random positions:
top_position = Math.random()*400; left_position = Math.random()*400;
this_img.style.top = top_position + "px";
this_img.style.left = left_position + "px";
theLeftSide.appendChild(this_img);
Here is the fiddle: https://jsfiddle.net/v222wgav/1/
This is how you generate random top_position locations and random left_position locations.
You should be able to modify the code below to suit your needs.
I've included a random function getRandom which is just a standard "get a random number within this range" function.
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
To use it, just provide a minimum number of pixels, and a maximum number of pixels in the range you need.
getRandom(0, 400);
var numberOfFaces=5;
var top_position = getRandom(0, 400);
var left_position = getRandom(0, 400);
var theLeftSide = document.getElementById("leftSide");
var i = 0;
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function generateFaces()
{
while(i < numberOfFaces)
{
var this_img = document.createElement("img");
this_img.src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/fb/718smiley.svg/60px-718smiley.svg.png";
this_img.style.top = top_position + "px";
this_img.style.left = left_position + "px";
theLeftSide.appendChild(this_img);
top_position = getRandom(0, 400);
left_position = getRandom(0, 400);
i++;
}
}
img {
position:absolute
}
div {
width:500px;height:500px
}
#rightSide {
position:absolute;
left: 0px;
top: 0px;
border-right: 1px solid black
}
<!DOCTYPE html>
<html>
<body onload="generateFaces()">
<div id="leftSide"></div>
<div id="rightSide"></div>
</body>
</html>
I would do away with the #rightSide div all together like so:
var numberOfFaces=5;
var top_position = getRandom(0, 400);
var left_position = getRandom(0, 400);
var theLeftSide = document.getElementById("leftSide");
var i = 0;
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function generateFaces()
{
while(i < numberOfFaces)
{
var this_img = document.createElement("img");
this_img.src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/fb/718smiley.svg/60px-718smiley.svg.png";
this_img.style.top = top_position + "px";
this_img.style.left = left_position + "px";
theLeftSide.appendChild(this_img);
top_position = getRandom(0, 400);
left_position = getRandom(0, 400);
i++;
}
}
img {
position:absolute
}
div {
width:500px;height:500px
}
#leftSide {
border-right: 1px solid black
}
<!DOCTYPE html>
<html>
<body onload="generateFaces()">
<div id="leftSide"></div>
</body>
</html>
Happy Random Smilies!
Resources:
Image Credit: https://commons.wikimedia.org/wiki/File:718smiley.svg
How to use generate random numbers in a specific range
How can the code below be modified such that when the progress bar is finished loading and it reaches the end, a seperate function (ie. test() )can be executed rather than just repeating and repeating like it is now.
<html>
<head>
<script type="text/javascript">
var prg_width = 200;
function progress() {
var node = document.getElementById('progress');
var w = node.style.width.match(/\d+/);
if (w == prg_width) {
w = 0;
}
node.style.width = parseInt(w) + 5 + 'px';
}
</script>
</head>
<body onload="var progress_run_id = setInterval(progress, 30);">
<div style="border: 1px solid #808080; width:200px; height:5px;">
<div id="progress" style="height:5px; width:0px; background-color:#DBDBDB;"/>
</div>
</body>
</html>
Much thanks and appreciation for all your help.
Cheers,
Jay
Call this separate function instead of
w = 0;
line. Don't forget to clearInterval(progress_run_id) too.
<html>
<head>
<script type="text/javascript">
var prg_width = 200;
var progress_run_id = null;
function progress() {
var node = document.getElementById('progress');
var w = node.style.width.match(/\d+/);
if (w == prg_width) {
clearInterval( progress_run_id );
w = 0;
} else {
w = parseInt(w) + 5 + 'px';
}
node.style.width = w;
}
function initialize(){
progress_run_id = setInterval(progress, 30);
}
window.onload = initialize();
</script>
</head>
<body>
<div style="border: 1px solid #808080; width:200px; height:5px;">
<div id="progress" style="height:5px; width:0px; background-color:#DBDBDB;"/>
</div>
</body>
</html>
var prg_width = 200;
function progress() {
var node = document.getElementById('progress');
var w = node.style.width.match(/\d+/);
if (w == prg_width) {
test(); // CHANGE THIS
clearInterval(progress_run_id);
}
node.style.width = parseInt(w) + 5 + 'px';
}
That checks if the width is equal to the completed width. If it is, then clear the interval, and call your test function.
<script type="text/javascript">
var prg_width = 200;
function progress() {
var node = document.getElementById('progress');
var w = node.style.width.match(/\d+/);
if (w == prg_width) {
test();
clearInterval(progress_run_id);
}
node.style.width = parseInt(w) + 5 + 'px';
}
</script>