I want the div to slide from left to right, and then back again from right left when it reaches the end of the browser using JavaScript.
var imgObj = null;
var animate;
function init() {
imgObj = document.getElementById('animate');
imgObj.style.position = 'fixed';
imgObj.style.left = '0px';
moveRight();
}
function moveRight() {
imgObj.style.left = parseInt(imgObj.style.left) + 1 + '%';
if (imgObj.style.left == '95%') {
clearTimeout(animate)
alert("i am here")
moveLeft();
}
animate = setTimeout(moveRight, 20);
}
function moveLeft() {
imgObj.style.left = parseInt(imgObj.style.left) - 1 + '%';
if (imgObj.style.right == '95%') {
clearTimeout(animate)
alert('i am here2')
moveRight();
}
animate = setTimeout(moveLeft, 20);
}
window.onload = init;
#animate {
width: 5%;
height: 10%;
background-color: red;
}
<div id="animate"></div>
This is an example of a similar animation, started by the button.You should always use variables to change values and not just hardcorde values to elements. In this case pos is the variable that gets changed (pos++ and pos--) and then added to the style-property.
In your Code i think you never stop increasing the % value. So it gets stuck in a scenario where it does +1 -1 +1 -1 forever.
function myMove() {
var elem = document.getElementById("myAnimation");
var pos = 0;
var id = setInterval(frame, 10);
function frame() {
if (pos == 100) {
clearInterval(id);
alert("done");
myMove2();
} else {
pos++;
elem.style.left = pos + '%';
}
}
}
function myMove2() {
var elem = document.getElementById("myAnimation");
var pos = 100;
var id = setInterval(frame, 10);
function frame() {
if (pos == 0) {
clearInterval(id);
alert("done2");
myMove();
} else {
pos--;
elem.style.left = pos + '%';
}
}
}
#myAnimation {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
<p>
<button onclick="myMove()">Click Me</button>
</p>
<div id ="myAnimation"></div>
I am new to programming but trying to solve a problem.
I am trying to increase a progress bar as I press on the "d" button. I am trying to do it recursively but I don't have enough skills to do it properly. Any help would be greately appreciated.
My js file looks like this so far:
window.addEventListener('keypress', function(e) {
function counter(p) {
//if the button is "d"
if (e.keyCode === 100) {
//target progressbar width and increase it
$('#progressbar').css('width', function(index, value) {
return $("#progressbar").css('width', ((p * 2) + "%"));
});
if ($('#progressbar').width() < 100) {
return counti(p + 1)
}
}
};
counti(1);
});
My html:
<div id = "myProgress" >
<div id = "progressbar" > 0 / 50 </div>
</div>
var count = 0;
var maxCount = 50;
var progressBar = document.getElementById("progressbar")
window.addEventListener("keypress", function(e) {
//if the button is "d"
if (e.keyCode === 100) {
// increase count if it's less than maxCount
count = count === maxCount ? maxCount : count + 1;
//target progressbar width and increase it
var newWidth = (count / maxCount) * 100 + "%";
progressBar.style.width = newWidth;
progressBar.innerHTML = count + "/" + maxCount
}
});
#myProgress {
width: 400px;
height: 30px;
background-color: #e4e4e4;
}
#progressbar {
width: 0%;
height: 30px;
background-color: #5980a7;
color: #fff;
}
<div id="myProgress">
<div id="progressbar">0/50</div>
</div>
Hi I have this working java script progress bar which shows progress bar as int.
I want to display the result of percentage as decimal?I have searched a lot in google and stack overflow didn't get what I want.
<html>
<head>
<style>
#myProgress {
width: 100%;
background-color: #ddd;
}
#myBar {
width: 0%;
height: 30px;
background-color: #4CAF50;
text-align: center;
line-height: 30px;
color: white;
}
</style>
</head>
<body>
<h1>JavaScript Progress Bar</h1>
<div id="myProgress">
<div id="myBar">0%</div>
</div>
<button onclick="move()">Click Me</button>
<script>
function move() {
var elem = document.getElementById("myBar");
var width = 0;
var id = setInterval(frame, 10);
function frame() {
if (width >= 10) {
clearInterval(id);
} else {
width++;
elem.style.width = width + '%';
elem.innerHTML = width *1 + '%'; //want this result as decimal
}
}
}
</script>
</body>
</html>
There you go, buddy. Change the JS as follows (and read the comments):
function move() {
var elem = document.getElementById("myBar");
var width = 0;
var id = setInterval(frame, 1); //change the setInterval from 10ms to 1ms, or whatever value you want to make it faster/slower
function frame() {
if (width >= 10) {
clearInterval(id);
} else {
width += 0.1; //change the increment value to 0.1 instead of 1
width = Math.round(width * 10) / 10; // round to nearest decimal
elem.style.width = width + '%';
elem.innerHTML = width + '%';
}
}
}
i have a progress bar which has to finish at 100%, and this moment the number shows this progress, the problem is this number is 1.5(it has to show 0.1, 0,2 and so on till number - 1.5) and I don't know how bind the progress bar with this number
$(function() {
var x = document.getElementById("load");
var width = 0;
x.innerHTML = width;
var int = setInterval(move, 20);
function move() {
if (width == 100) {
clearInterval(int);
} else {
width += 1;
x.style.width = width + "%";
x.innerHTML = width + "%";
}
}
});
Do width/100 and use toFixed() to determine the number of decimals.
$(function() {
var x = document.getElementById("load");
var width = 0;
x.innerHTML = width;
var int = setInterval(move, 20);
function move() {
if (width == 100) {
clearInterval(int);
} else {
width += 1;
x.style.width = width + "%";
x.innerHTML = ((width / 100).toFixed(1)) + "%";
}
}
});
#load {
position: fixed;
height: 100%;
display: flex;
align-items: center;
background-color: #000;
color: #fff;
font-size: 50px;
justify-content: flex-end;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="load" />
This is more a math problem than a scripting one...
You have to tell the script that 1.5 is 100%.
I only added one line to your script in order to change the inner HTML displayed.
var showNumber = (1.5/100)*width;
x.innerHTML = showNumber.toFixed(1);
$(function() {
var x = document.getElementById("load");
var width = 0;
x.innerHTML = width;
var int = setInterval(move, 200); // Setted a longer delay...
function move() {
if (width == 100) {
clearInterval(int);
} else {
width += 1;
x.style.width = width + "%";
var showNumber = (1.5/100)*width;
x.innerHTML = showNumber.toFixed(1); // Only one decimal.
}
}
});
#load{
background-color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="load"></div>
There's a div (brown rectangle) on the page. The page is higher than the viewport (orange rectangle) so it can be scrolled, which means that the div might only partially show up or not at all.
What's the simplest algorithm to tell how much % of the div is visible in the viewport?
(To make things easier, the div always fits into the viewport horizontally, so only the Y axis needs to be considered at the calculations.)
See one more example in fiddle:
https://jsfiddle.net/1hfxom6h/3/
/*jslint browser: true*/
/*global jQuery, window, document*/
(function ($) {
'use strict';
var results = {};
function display() {
var resultString = '';
$.each(results, function (key) {
resultString += '(' + key + ': ' + Math.round(results[key]) + '%)';
});
$('p').text(resultString);
}
function calculateVisibilityForDiv(div$) {
var windowHeight = $(window).height(),
docScroll = $(document).scrollTop(),
divPosition = div$.offset().top,
divHeight = div$.height(),
hiddenBefore = docScroll - divPosition,
hiddenAfter = (divPosition + divHeight) - (docScroll + windowHeight);
if ((docScroll > divPosition + divHeight) || (divPosition > docScroll + windowHeight)) {
return 0;
} else {
var result = 100;
if (hiddenBefore > 0) {
result -= (hiddenBefore * 100) / divHeight;
}
if (hiddenAfter > 0) {
result -= (hiddenAfter * 100) / divHeight;
}
return result;
}
}
function calculateAndDisplayForAllDivs() {
$('div').each(function () {
var div$ = $(this);
results[div$.attr('id')] = calculateVisibilityForDiv(div$);
});
display();
}
$(document).scroll(function () {
calculateAndDisplayForAllDivs();
});
$(document).ready(function () {
calculateAndDisplayForAllDivs();
});
}(jQuery));
div {
height:200px;
width:300px;
border-width:1px;
border-style:solid;
}
p {
position: fixed;
left:320px;
top:4px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1">div1</div>
<div id="div2">div2</div>
<div id="div3">div3</div>
<div id="div4">div4</div>
<p id="result"></p>
Here's a snippet illustrating how you can calculate this.
I've put the % values in the boxes for readability, and it even kinda "follows" the viewport ^^ :
Fiddle version
function listVisibleBoxes() {
var results = [];
$("section").each(function () {
var screenTop = document.documentElement.scrollTop;
var screenBottom = document.documentElement.scrollTop + $(window).height();
var boxTop = $(this).offset().top;
var boxHeight = $(this).height();
var boxBottom = boxTop + boxHeight;
if(boxTop > screenTop) {
if(boxBottom < screenBottom) {
//full box
results.push(this.id + "-100%");
$(this).html("100%").css({ "line-height": "50vh" });
} else if(boxTop < screenBottom) {
//partial (bottom)
var percent = Math.round((screenBottom - boxTop) / boxHeight * 100) + "%";
var lineHeight = Math.round((screenBottom - boxTop) / boxHeight * 50) + "vh";
results.push(this.id + "-" + percent);
$(this).html(percent).css({ "line-height": lineHeight });
}
} else if(boxBottom > screenTop) {
//partial (top)
var percent = Math.round((boxBottom - screenTop) / boxHeight * 100) + "%";
var lineHeight = 100 - Math.round((boxBottom - screenTop) / boxHeight * 50) + "vh";
results.push(this.id + "-" + percent);
$(this).html(percent).css({ "line-height": lineHeight });
}
});
$("#data").html(results.join(" | "));
}
$(function () {
listVisibleBoxes();
$(window).on("scroll", function() {
listVisibleBoxes();
});
});
body {
background-color: rgba(255, 191, 127, 1);
font-family: Arial, sans-serif;
}
section {
background-color: rgba(175, 153, 131, 1);
height: 50vh;
font-size: 5vh;
line-height: 50vh;
margin: 10vh auto;
overflow: hidden;
text-align: center;
width: 50vw;
}
#data {
background-color: rgba(255, 255, 255, .5);
left: 0;
padding: .5em;
position: fixed;
top: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="one"></section>
<section id="two"></section>
<section id="three"></section>
<section id="four"></section>
<section id="five"></section>
<section id="six"></section>
<div id="data">data here</div>
After playing around a bit I think I've found perhaps the simplest way to do it: I basically determine how much the element extends over the viewport (doesn't matter in which direction) and based on this it can easily be calculated how much of it is visible.
// When the page is completely loaded.
$(document).ready(function() {
// Returns in percentages how much can be seen vertically
// of an element in the current viewport.
$.fn.pvisible = function() {
var eTop = this.offset().top;
var eBottom = eTop + this.height();
var wTop = $(window).scrollTop();
var wBottom = wTop + $(window).height();
var totalH = Math.max(eBottom, wBottom) - Math.min(eTop, wTop);
var wComp = totalH - $(window).height();
var eIn = this.height() - wComp;
return (eIn <= 0 ? 0 : eIn / this.height() * 100);
}
// If the page is scrolled.
$(window).scroll(function() {
// Setting the opacity of the divs.
$("div").each(function() {
$(this).css("opacity", Math.round($(this).pvisible()) / 100);
});
});
});
html,
body {
width: 100%;
height: 100%;
}
body {
background-color: rgba(255, 191, 127, 1);
}
div {
width: 60%;
height: 30%;
margin: 5% auto;
background-color: rgba(175, 153, 131, 1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
A little illustration to help understand how it works:
Chrome now supports Intersection Observer API
Example (TypeScript):
export const elementVisibleInPercent = (element: HTMLElement) => {
return new Promise((resolve, reject) => {
const observer = new IntersectionObserver((entries: IntersectionObserverEntry[]) => {
entries.forEach((entry: IntersectionObserverEntry) => {
resolve(Math.floor(entry.intersectionRatio * 100));
clearTimeout(timeout);
observer.disconnect();
});
});
observer.observe(element);
// Probably not needed, but in case something goes wrong.
const timeout = setTimeout(() => {
reject();
}, 500);
});
};
const example = document.getElementById('example');
const percentageVisible = elementVisibleInPercent(example);
Example (JavaScript):
export const elementVisibleInPercent = (element) => {
return new Promise((resolve, reject) => {
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
resolve(Math.floor(entry.intersectionRatio * 100));
clearTimeout(timeout);
observer.disconnect();
});
});
observer.observe(element);
// Probably not needed, but in case something goes wrong.
const timeout = setTimeout(() => {
reject();
}, 500);
});
};
const example = document.getElementById('example');
const percentageVisible = elementVisibleInPercent(example);
Please note that the Intersection Observer API is available since then, made specifically for this purpose.