My HTML, CSS and JS progress bar doesn't work - javascript

I'm trying to do a progress bar so that the users can know when will their file be downloaded. I don't know what I did wrong, but the progress bar style doesn't update in the for loop.
var filesize = 1000 //this is not the final value
var progressbar = document.getElementById("progress");
function myFunction(){
for(var i = 0; i <= filesize; i++){
x = i/ filesize * 100;
x = parseInt(x.toString().slice(0, 3));
console.log(x + "%")
progressbar.style.width = x + "%";
}
}
#bar{
width: 35%;
background-color: rgba(0,0,0,0.17);
border-radius: 130px;
margin: auto;
}
#progress{
width: 0%;
height: 30px;
background-color: rgb(255, 0, 0);
border-radius: 130px;
}
<button onclick="myFunction()">Click me</button>
<div id="bar">
<div id="progress"></div>
</div>

You can make the progress bar move smoothly by adding the transition property in CSS.
A higher transition time will result in the progress bar moving slower.
var filesize = 1000 //this is not the final value
var progressbar = document.getElementById("progress");
function myFunction() {
for (var i = 0; i <= filesize; i++) {
x = i/ filesize * 100;
x = parseInt(x.toString().slice(0, 3));
console.log(x + "%")
progressbar.style.width = x + "%";
}
}
#bar {
width: 35%;
background-color: rgba(0,0,0,0.17);
border-radius: 130px;
margin: auto;
}
#progress {
width: 0%;
height: 30px;
background-color: rgb(255, 0, 0);
border-radius: 130px;
transition: 0.2s;
}
<button onclick="myFunction()">Click me</button>
<div id="bar">
<div id="progress">
</div>
</div>

Related

Optimized solution for filling entire page with DIVs

I want to have a webpage whose entire viewable area is filled with divs. I am currently using the following code:
var wh= window.innerHeight;
var ww= window.innerWidth;
var area= wh * ww;
i= 1;
while(area > 0) {
document.getElementById("map").innerHTML+= "<div class='map-box' id='box" + i + "'></div>";
area-= 20 * 20;
i+=1;
}
.map-box {width: 20px; height: 20px; border-color: grey; border-width: 1px; border-style: solid; display: inline-block; margin: 0; padding: 0;}
<body>
<div id='map'></div>
</body>
If you try to use this code is your browser, you will see that there are two flaws in this:
First, it creates too many extra divs which go outside the viewable screen.
Second, this code is also somewhat slow.
Can someone here help me address both of these flaws and also optimize this code for faster performance?
1.) That <div> is not 20x20, because of the border:
let d = document.getElementById("test");
console.log(d.offsetWidth, d.offsetHeight);
.map-box {
width: 20px;
height: 20px;
border-color: grey;
border-width: 1px;
border-style: solid;
display: inline-block;
margin: 0;
padding: 0;
}
<div id="test" class="map-box"></div>
2.) There's still the default border around the entire thing, and also some spacing between the lines:
var wh = window.innerHeight;
var ww = window.innerWidth;
var area = wh * ww;
i = 1;
while (area > 0) {
document.getElementById("map").innerHTML += "<div class='map-box' id='box" + i + "'></div>";
area -= 22 * 22; // hardcoding is not that nice
i += 1;
}
.map-box {
width: 20px;
height: 20px;
border-color: grey;
border-width: 1px;
border-style: solid;
display: inline-block;
margin: 0;
padding: 0;
}
#map {
background: blue;
}
body {
background: red;
}
<div id='map'></div>
3.) Half cells are evil, so the width/height should be rounded downwards to a multiple of 22. Suddenly the grid is becoming an actual rectangle, at least in Chrome/Edge. The between-spacing is still a problem:
var wh = Math.floor(window.innerHeight / 22) * 22; // <--!!
var ww = Math.floor(window.innerWidth / 22) * 22; // <--!!
var area = wh * ww;
i = 1;
while (area > 0) {
document.getElementById("map").innerHTML += "<div class='map-box' id='box" + i + "'></div>";
area -= 22 * 22;
i += 1;
}
.map-box {
width: 20px;
height: 20px;
border-color: grey;
border-width: 1px;
border-style: solid;
display: inline-block;
margin: 0;
padding: 0;
}
#map {
background: blue;
}
body {
background: red;
margin: 0; // <--!!
padding: 0; // <--!!
}
<div id='map'></div>
I don't actually know how to use line-height properly, this one works on my machine with my scaling/DPI, in Chrome/Edge, but that's all I can say about it. The 22-s are cut back, area now simply stores the number of <div>s to generate.
var wh = Math.floor(window.innerHeight / 22);
var ww = Math.floor(window.innerWidth / 22);
var area = wh * ww;
i = 1;
while (area > 0) {
document.getElementById("map").innerHTML += "<div class='map-box' id='box" + i + "'></div>";
area--;
i += 1;
}
.map-box {
width: 20px;
height: 20px;
border-color: grey;
border-width: 1px;
border-style: solid;
display: inline-block;
margin: 0;
padding: 0;
}
#map {
line-height: 0.6;
}
body {
margin: 0;
padding: 0;
}
<div id='map'></div>
Instead of accessing dom element's inner html on each loop iteration - do it once after the loop with "prepared" data to set there
const wh = window.innerHeight;
const ww = window.innerWidth;
let area = wh * ww;
i = 1;
const ms = Date.now();
const divs = [];
while (area > 0) {
divs.push("<div class='map-box' id='box" + i + "'></div>");
area -= 20 * 20;
i += 1;
}
document.getElementById("map").innerHTML = divs.join("");
console.log("done fast", Date.now() - ms);
js fiddle with comparison https://jsfiddle.net/aL7zqwy9/
The final solution, not ideal but
<html>
<body>
<div id='map'></div>
</body>
<style>
body {
margin: 0;
padding: 0;
/* Overflow appears when last row is added and shrinks the "width" */
overflow-y: hidden;
}
#map {
/* To exclude space between rows */
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
.map-box {
width: 20px;
height: 20px;
border: 1px solid grey;
display: block;
margin: 0;
padding: 0;
/* So border thickness will not affect element size */
box-sizing: border-box;
}
</style>
<script>
const cellSize = 20; // px
const wh = window.innerHeight;
const ww = window.innerWidth;
// not always divisible by cell size without a remainder
const columnsCount = Math.floor(ww / cellSize);
const rowsCount = Math.floor(wh / cellSize);
const cellsCount = columnsCount * rowsCount;
console.log(`wh: ${wh}, ww: ${ww}, cols: ${columnsCount}, rows: ${rowsCount}`);
const divs = [];
for (let i = 0; i < cellsCount; i++) {
divs.push(`<div class='map-box' id='box${i}'></div>`);
}
document.getElementById("map").innerHTML = divs.join("");
</script>
</html>

Covering the entire div's with HTMl divs

Supoose the screen size is 1920by1080, then I want div of user input suppose say 200by200
then these div's of this dimensions should create the entire screen. How can i do that using HMTL, CSS and javascript.
CSS CODE
div {
height: 200px;
width: 200px;
background-color: red;
padding-bottom: 20px;
box-shadow: 2px 2px 8px rgba(0, 0, 0, 0.3);
border-style: solid;
display: inline-block;
}
HTML CODE
<input type="number" placeholder="enter height of div" id="div_height" />
<input type="number" placeholder="enter width of div" id="div_width" />
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
JAVASCRIPT
function myFunction() {
let height_div = document.getElementById('div_height').value;
let width_div = document.getElementById('div_width').value;
var xy = '',
i,
size = 20;
var x = screen.availHeight;
var y = screen.availWidth;
while (x > height_div) {
while (y > width_div) {
xy = xy + '<div>' + '</div>';
y = y - width_div;
}
x = x - height_div;
}
document.getElementById('demo').innerHTML = xy;
console.log(height_div + ' ' + width_div);
document.getElementsByTagName('div').style.height = height_div + 'px';
document.getElementsByTagName('div').style.width = width_div + 'px';
OUTPUT
Try using this code:
div
{
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
Then it would cover entire screen.
function myFunction(e) {
e.preventDefault()
let height_div = document.getElementById("div_height").value;
let width_div = document.getElementById("div_width").value;
var xy = "";
const xi = Math.floor(window.innerWidth / width_div);
const yi = Math.floor(window.innerHeight / height_div);
for (let i = 0; i < yi; i++) {
xy += "<div class='row'>";
for (let j = 0; j < xi; j++) {
xy += "<div></div>"
}
xy += '</div>'
}
console.log(xy)
document.getElementById("demo").innerHTML = xy;
console.log(height_div + " " + width_div);
Array.from(document.getElementsByTagName("div")).map(el => (el.style.height = height_div + "px"));
Array.from(document.getElementsByTagName("div")).map(el => (el.style.width = width_div + "px"));
}
document.querySelector("form").addEventListener('submit', myFunction);
div {
box-sizing: border-box;
height: 200px;
width: 200px;
background-color: red;
box-shadow: 2px 2px 8px rgba(0, 0, 0, 0.3);
border-style: solid;
flex-grow: 0;
flex-shrink: 0;
}
.row {
display: flex;
}
p#demo {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
margin: 0;
z-index: 1;
}
.form {
background: blue;
position: relative;
z-index: 2;
}
<form class="form">
<input type="number" placeholder="enter height of div" id="div_height" />
<input type="number" placeholder="enter width of div" id="div_width" />
<button>Try it</button>
</form>
<p id="demo"></p>
Try something like this,
you can use Math.ceiling if you want to fill the white gaps and have a little hangover

Is there a way to stop my character going off the screen?

I have a game with a character that goes to a random position whenever you click on it. Also, I made it so the game automatically goes into full-screen. However, sometimes, the character goes way off-screen and (because there are no scroll bars in full-screen) you cant get to it. The code is below.
<!doctype html>
<html>
<head>
<link href='https://fonts.googleapis.com/css?family=Alfa Slab One' rel='stylesheet'> <!-- add the font used -->
<script type="text/javascript">
function move() { //move the bird
const height = screen.height; //set the screen params
const width = screen.width;
const box = document.getElementById("bird"); //search for the bird
let randY = Math.floor((Math.random() * height) + 1); //randomise the coords
let randX = Math.floor((Math.random() * width) + 1);
box.style.transform = `translate(${randX}px, ${randY}px)`; //move the bird
addScore(); //add the score
}
</script>
<script type="text/javascript">
function getreqfullscreen(){ //full screen it. I cant really understand how it works
var root = document.documentElement
return root.requestFullscreen || root.webkitRequestFullscreen || root.mozRequestFullScreen || root.msRequestFullscreen
}
function startFullScreen() {
var pagebody = document.getElementById("main");
var globalreqfullscreen = getreqfullscreen();
document.addEventListener('click', function(e){
var target = e.target
globalreqfullscreen.call(pagebody)
}, false)
}
</script>
<script type="text/javascript">
var points = 0;
function addScore() { //add the score
var pointcount = document.getElementById("scoreCount"); //get the score counter
//var points = 45; --used for testing
points = points + 1; //increment the points
pointcount.innerText = "score: " + points;
//pointCounter.removeChild(pointCounter.childNodes[0]); --used for an older prototype
}
/**************************************/
function startCountdown() { //initiate the timer - starts when the <body> loads
startFullScreen(); //make it full screen
var time = 9999999999999999999999; //would be 60, but I made it infinite
setInterval(function() { //decrease every second
var timer = document.getElementById("Timer"); //get the timer
time = time - 1; //decrement the timer
timer.innerText = "time: " + time;
if(time == 0) { //if you finished
var continuE = prompt("Would you like to restart? (type Y for yes and N for no (case sensitive)).");
if(continuE == "Y") {
window.location.reload();
} else {
history.go(-1);
}
}
},1000);
}
</script>
<style>
html {
cursor: crosshair;
background-color: #00b0e6;
user-select: none;
}
#bird {
position: absolute;
background-color: #ffffff;
cursor: crosshair;
transition: all 1s ease-in-out;
}
#bird:hover {
invert: 0 0 12px #ff0000;
}
/*
span {
height:10px;ss
width:200px;
border:5px double red;
color:#ff00ff;
background-color:#00ffff;
}
*/
p {
color: #ff00ff;
background-color: #000000;
border: 5px double red;
height: 60px;
width: 85px;
margin: 10px;
font-family: "Times New Roman";
}
.restartButton {
border-radius: 999px;
background-color: #ff00ff;
color: #00fffff;
border: 10px double blue;
transition: all 1s ease-out;
margin-left: 50%;
margin-right: 50%;
position: relative;
cursor: help;
}
.restartButton:hover {
border-radius: 999px;
background-color: #ffffff;
color: #4500fff;
border: 10px solid red;
}
#scoreCount {
color: #aff823;
position: fixed;
top: 0;
width: 10px;
height: 10px;
}
#Timer {
color: #aff823;
position: fixed;
top: 0;
left: 200px;
width: 10px;
height: 10px;
}
span {
font-family: Alfa Slab One;
}
#main {
background-color: #00b0e6;
}
</style>
</head>
<body onload="startCountdown()" id="body">
<div id="main">
<div id="pointCounter"><span id="scoreCount"></span><span id="Timer"></span></div>
<input type="button" value="RESTART" onclick="window.location.reload();" class="restartButton"/>
<img src="https://art.pixilart.com/81a784782ea5697.png" alt="" height="50px" width="50px" id="bird" onclick="move();">
</div>
<noscript>
YOU DO NOT HAVE JAVASCRIPT ENABLED. PLEASE ENABLE JAVASCRIPT ELSE THIS WEB PAGE WILL NOT WORK.
</noscript>
</body>
</html>
Because of how stack overflow works, it doesn't go into full-screen.
P.S. I have made it infinite time, it's meant to only be 60 seconds.

progress bar is not working

i am trying to made progress bar but its can working plz solve it .
i am using if else for increasing the width but it's not working
var x = document.getElementById("p_bar");
for(var i = 0; i < 100; i++) {
var wid;
wid=1;
if(wid == 800)
break;
else
wid+=8;
x.style.width=wid+"px";
}
document.body.style.background = "#"+((1<<24)*Math.random()|0).toString(16);
#cont {
width: 800px;
height: 30px;
background-color: cornsilk;
position: relative;
}
#p_bar {
width: 8px;
height: 30px;
background-color: red;
position: absolute;
}
<div id="cont">
<div id="p_bar"></div>
</div>
<p id="write"></p>
var x=document.getElementById("p_bar");
var wid = 1;
var it = setInterval(function(){
if(wid <= 800){
wid+=8;
x.style.width=wid+"px";
}else{
clearInterval(it);
}
}, 1000);
document.body.style.background = "#"+((1<<24)*Math.random()|0).toString(16);
#cont{
width: 800px;
height: 30px;
background-color: cornsilk;
position: relative;
}
#p_bar{
width: 8px;
height: 30px;
background-color: red;
position: absolute;
}
<div id="cont">
<div id="p_bar"></div></div>
<p id="write"></p>
If you want to see moving progress bar, You should use setInterval().
If you use just for, you can't see any animation.
Because, computer's calculating is so fast, so you can see only the result of for
I wrote it again using functions, try this shubham:
var x = document.getElementById('p_bar');
var container = document.getElementById('cont');
var write = document.getElementById('write');
var containerWidth = container.offsetWidth;
var currentWidth = x.offsetWidth;
var compeleteProgress = function (step, every) {
currentWidth = Math.min(currentWidth + step, containerWidth);
write.innerHTML = Math.floor((currentWidth / containerWidth) * 100) + '%' // Priniting percentage
x.style.width = currentWidth + 'px'
if (currentWidth < containerWidth) setTimeout(function () {
compeleteProgress(step, every)
}, every)
}
compeleteProgress(8, 300) // When you call this function, everything starts
document.body.style.background = "#"+((1<<24)*Math.random()|0).toString(16);
#cont{
width: 800px;
height: 30px;
background-color: cornsilk;
position: relative;
}
#p_bar{
width: 8px;
height: 30px;
background-color: red;
position: absolute;
}
<div id="cont">
<div id="p_bar"></div>
</div>
<p id="write"></p>
I am not sure what behavior you really expects. The Bar size is usually changed according to any application events (in my example by timeouts). I hope this helps:
document.body.style.background = "#"+((1<<24)*Math.random()|0).toString(16);
var setBarWidthInPercent = function(barId, value){
var bar=document.getElementById(barId);
bar.style.width = value+"%";
}
setTimeout(function(){
setBarWidthInPercent("p_bar",10)
},500)
setTimeout(function(){
setBarWidthInPercent("p_bar",50)
},1500)
setTimeout(function(){
setBarWidthInPercent("p_bar",100)
},3000)
#cont{
width: 800px;
height: 30px;
background-color: cornsilk;
position: relative;
}
#p_bar{
width: 8px;
height: 30px;
background-color: red;
position: absolute;
-webkit-transition: width 1s ease-in-out;
-moz-transition: width 1s ease-in-out;
-o-transition: width 1s ease-in-out;
transition: width 1s ease-in-out;
}
<div id="cont">
<div id="p_bar"></div></div>
<p id="write"></p>

How to create (or at least, describe) horizontal progress bar with thresholds?

I'm looking to create a horizontal chart with thresholds at certain percentages- if you've ever used Battle.Net, kind of similar to their download bar:
Blizzard Download Bar
I'm sure there's a name for it, I just don't know what it is...
Thanks!
I made this just in case it helps. Have 'fun'.
You can edit the little threshold pointer so they look stylish with css. But yea that all depends on what you want to do
// Btw, I'm a big fan of the canvas element that's why I'm doing this. Otherwise, you can also use a progress bar
var c = document.getElementById('progressBar'),
dt = document.getElementById('download-text'),
btn = document.querySelector('button'),
p2 = document.querySelector('progress');
var cx = c.getContext('2d');
var counter = 0,
loop;
btn.onclick = function() {
btn.innerText = 'N';
var timeInter = setInterval(function(){
btn.innerText += 'o';
},70);
setTimeout(function(){
clearTimeout(timeInter);
btn.hidden = true;
p2.hidden = false;
progress2();
},1000);
}
var loop2 = '',
counter2 = 0;
function progress2() {
counter2++;
var percentage = (counter2 / 17).toFixed(2);
if (percentage - 0 >= 100) {
percentage = 100;
}
p2.value = percentage - 0 +'';
if (percentage - 0 > 100) {
cancelAnimationFrame(loop2);
} else {
loop2 = requestAnimationFrame(progress);
}
//This is me failing to animate the progress bar
}
function progress() {
counter++;
var percentage = (counter / 17).toFixed(2);
if (percentage >= 100) {
percentage = 100+'.00';
}
dt.innerText = "Download: " + percentage + "%";
cx.fillStyle = '#00FFFF';
cx.fillRect(0, 0, c.width * percentage / 100, c.height);
cx.strokeStyle = '#ccc';
cx.beginPath();
cx.moveTo(100, 70);
cx.lineTo(100, 0);
cx.stroke();
cx.moveTo(300, 70);
cx.lineTo(300, 0);
cx.stroke();
if (percentage - 0 > 100) {
cancelAnimationFrame(loop);
} else {
loop = requestAnimationFrame(progress);
}
}
progress();
#progressBar {
border: 1px solid grey;
z-index: -10;
}
#progressBar,
#download-text,
#playable,
#optimal,
button,
progress{
position: absolute;
top: 0px;
left: 0px;
}
button,
progress{
top:200px;
}
#download-text {
height: 70px;
padding-top: 25px;
padding-left: 7px;
font-family: sans-serif;
background-color: transparent;
}
#playable,
#optimal {
width: 100px;
height: 43px;
text-align: center;
padding-top: 20px;
font-family: sans-serif;
font-weight: bolder;
}
#playable {
background-color: yellow;
position: absolute;
top: 72px;
left: 100px;
}
#optimal {
background-color: green;
position: absolute;
top: 72px;
left: 300px;
}
<div>
<canvas id="progressBar" width="430px" height="70px"></canvas>
<div id="download-text">Hello</div>
</div>
<div id="playable">PLAYABLE</div>
<div id="optimal">OPTIMAL</div>
<button type="button">Please don't press me just stick to canvas</button>
<progress max="100" hidden="true"></progress>

Categories