HTML5 progress bar animation - html

I am using an HTML5 progress bar in my app. I would like to know if there is any way to control the animation speed of the progress bar. I want to show the progress after a certain interval, which I did using the setTimeout method of javascript so that it sets the value after the screen has been rendered. But the animation is too fast. Is there any way to control it?
Thanks.

I'm not sure I understand what you mean by "animation" but here is an example of using the progress bar while controlling the speed of progression: http://jsfiddle.net/526hM/
Html:
<progress max="200" value="1"></progress>
<div id="val"></div>
Script:
$(document).ready(function(){
var interval = 2, //How much to increase the progressbar per frame
updatesPerSecond = 1000/60, //Set the nr of updates per second (fps)
progress = $('progress'),
animator = function(){
progress.val(progress.val()+interval);
$('#val').text(progress.val());
if ( progress.val()+interval < progress.attr('max')){
setTimeout(animator, updatesPerSecond);
} else {
$('#val').text('Done');
progress.val(progress.attr('max'));
}
}
setTimeout(animator, updatesPerSecond);
});

Here is example.
JavaScript function:
window.onload = addTenPercent();
function addTenPercent() {
var bar = document.getElementById("progressBar");
setInterval(addTenPercent, 100);
bar.value += 5;
};
HTML:
<progress id="progressBar" max="100" value="0"></progress>

Mantas' answer above looks good and works (without having to use jQuery), but I wonder if we could also use the setTimeout function? Would setTimeout in a recursive function that exits after 100 iterations also work? Copying Mantas' code from above and changing it a little:
JavaScript:
function onWindowLoad(){ // to be called by onload event
var bar = document.getElementById("progressBar");
addOne();
}
function addOne() {
if (bar.value < 100) { // this is the max value of the bar and the # of iterations
setTimeout(addOne, 80); // this literal value controls the speed
bar.value += 1;
}else{
return;
}
}
HTML:
<progress id="progressBar" max="100" value="0"></progress>

Related

Random Image Position in programming website?

I want to make it so I have "enemies" spawn in the background (not THE background, just images on top of it) of a particular webpage at random heights and scroll across the screen. Right now I have something like:
<script>
function numberRandomizer(){
var x = Math.floor((Math.random() * 500) + 300); //random number between 300 and 800
return x;
}
</script>
I've tried 2 methods to applying this random variable X to the images that loop by scrolling on screen:
1) Doing what I thought would work and editing each image to get a random value for top and left
<marquee behavior="scroll" direction="left" scrollamount="numberRandomizer()"><img src="/aboutme/enemy.png" width="120" height="80" top="numberRandomizer()" left="numberRandomizer()"/><p></marquee>
2) Even though as far as I know it would make all enemies have the same position, try out CSS styling to make the placement random just to see if it would work:
<style>
img {
top: numberRandomizer();
left: numberRandomizer();
}
</style>
Neither style works in setting a random value for the image location, am I getting a minor thing wrong or going about this completely the wrong way?
As a bonus question: Is it possible to set marquee to go a random direction per image?
You can make the same thing using plain javascript too
html:
<marquee behavior="scroll" direction="left" id="elem">Test</marquee>
<br/>
<button id="butR">Right</button>
<button id="butL">Left</button>
<div class="area">
<div id="enemy"></div>
</div>
Js:
document.getElementById('butR').addEventListener("click", function(){
document.getElementById('elem').setAttribute("direction", "right");
});
document.getElementById('butL').addEventListener("click", function(){
document.getElementById('elem').setAttribute("direction", "left");
});
function numberRandomizer(){
var x = Math.floor((Math.random() * 250) + 50); //random number between 50 and 300
return x;
}
document.getElementById('enemy').style.top = numberRandomizer() + 'px';
document.getElementById('enemy').style.left = numberRandomizer() + 'px';
I've added also a way to change marque direction. Take a look at this fiddle:
https://jsfiddle.net/oyv324z9/
As a couple people said, you can't mix JS and CSS. If you are using jQuery though, this is pretty simple. Basically, you want to use jQuery to add CSS styles to the img. Something like this.
//your trigger here and then..
$( "#your_img_id" ).css( "left", function(index) {
return index * numberRandomizer() ;
});
$( "#your_img_id" ).css( "right", function(index) {
return index * numberRandomizer() ;
});

How do I create a Random Border Radius?

In the Javascript portion of The Complete Web Developer Course on Udemy, Rob (the teacher) makes a div randomly become either a circle or square based on a simple if-then statement. But how would I create a square with a completely random border radius?
function getRadius() {
var radius=Math.random();
radius = radius * 100;
}
function makeBox() {
var time=Math.random();
time=time*2000;
setTimeout(function() {
document.getElementById("box").style.borderRadius="50px";
document.getElementById("box").style.backgroundColor=getRandomColor();
document.getElementById("box").style.display="block";
createdTime=Date.now();
}, time);
}
The program works when I have just have an integer with px after like in the example, but I can't seem to figure out how to change the 50 to the function getRadius, if that makes sense. Nothing appears with
html:
<div id="box" onclick="change();">
<p>click me</p>
<div>
css:
#box{
height:100px;
width:100px;
background-color:red;
}
js:
function change(){
var num = Math.floor(Math.random() * 100);
box.style.borderRadius= num+'px';
};

How do I achieve arrow key navigation between divs

I have the following list of divs
<div id="multi-picker">
<div id="opt1">
<input type="checkbox"> Option 1
</div>
<div id="opt2">
<input type="checkbox"> Option 2
</div>
etc...
</div>
All working, but I'm not happy with the keyboard navigation. To navigate from opt1 to opt2 I need to press the tab key. Ideally I want to treat the options as a select and navigate with up/down arrow. Can this be done?
Alternatively...
Is there any way to have a multi-select with the options styled with checkboxes to reflect the selection state of each option?
I think you'll need javascript and using a plugin is an easier way to accomplish the task and maintain cross-browser functionality. However, here is a fiddle that, I think, kind of does what you want using just javascript. It defines additional attributes on your select elements and uses an onkeydown function to handle the navigation between the elements.
function keyPressed(e) {
var srcElement = e.target; // get the element that fired the onkeydown function
var dataset = false;
var selectList = false;
var next = "";
var prev = "";
if (srcElement.dataset) { // can we use HTML5 dataset?
dataset = true; // remember for later
// is this an element for which we care
if (srcElement.dataset.selectlist == 'true') {
selectList = true;
}
} else { // can't use HTML5 dataset, use getAttribute
if (srcElement.getAttribute('data-selectlist') == 'true') {
selectList = true;
}
}
// is it a select element and the user pressed either up arrow or down arrow
if (selectList && (e.keyCode == '38' || e.keyCode == '40')) {
// get the next and prev navigation options for this element
if (dataset) {
next = srcElement.dataset.next;
prev = srcElement.dataset.prev;
} else {
next = srcElement.getAttribute('data-next');
prev = srcElement.getAttribute('data-prev');
}
// up arrow was pressed and a prev element is defined
if (e.keyCode == '38' && prev != '') {
document.getElementById(prev).focus();
}
// down arrow was pressed and a next element is defined
if (e.keyCode == '40' && next != '') {
document.getElementById(next).focus();
}
// don't do native processing of the up or down arrow (page scrolling)
e.preventDefault;
}
}
document.onkeydown = keyPressed;
Here is the new html that contains the additional elements:
<div id="multi-picker">
<div id="opt1">
<input id="select1" type="checkbox" data-selectlist="true" data-prev="" data-next="select2"> Option 1
</div>
<div id="opt2">
<input id="select2" type="checkbox" data-selectlist="true" data-prev="select1" data-next=""> Option 2
</div>
</div>
This code is very specific to the problem presented and, though it may solve the problem, it would probably be better to use a general purpose plugin that would allow for more general application across your environment. You may also run into problems related to what your user expects the down and up arrow keys to do versus what you are doing by intercepting them.
In my experience I've run into problems where different browsers and even different end-user platforms present different behavior to the application making implementation consistency spotty. Many of the plugins are designed to eliminate that inconsistency and provide a cleaner, more intuitive interface.
Alternatively... Is there any way to have a multi-select with the options styled with checkboxes to reflect the selection state of each option?
That has multi-browser support? Not really. However, if you're a "It works in Chrome, it ships!" type dev, then you could totally fake a multi select to appear to have checkboxes that reflect the selection state of each option with good ol' CSS.
First our HTML:
<select multiple="multiple">
<option>Hello</option>
<option>World</option>
<option>Hello</option>
<option>World</option>
</select>
Next, dat CSS:
select {
border: none;
}
select:focus {
outline: none;
}
select option:before {
display: inline-block;
content: '';
width: 13px;
height: 13px;
position: relative;
margin-right: 3px;
background-image: url('http://i.imgur.com/5xszy3H.png');
background-position: -40px 0px;
top: 2px;
}
Using generated content, we've now applied our pseudo checkboxes. Let's add that last bit of CSS to give us a proper selected state!
select option:checked:before {
background-position: -40px -40px;
}
Woop.
Here's a fiddle to play around with: http://jsfiddle.net/9tLz6ugz/
In (limited) testing, this seemed to only work in Chrome and FireFox (both latest on OSX). Safari, IE, and Opera ignored the generated content all together. So, while not practical (at least not today), it's somewhat doable!
(Here's another fiddle without the background-image - requires a bit more work to get the look/feel consistent across browsers: http://jsfiddle.net/wpch98tg/ But does demonstrate use of unicode to fake a "checkbox" in a multi-select...)
I don't believe you'll find a way with plain HTML & CSS - this gets too far into customizing the core functionality so a bit of JavaScript should do the trick (I'm also using jQuery to make it slightly easier).
For my test, I used <label> instead of <div> to wrap the checkboxes, but this same idea holds true for divs. I just prefer labels so if JavaScript doesn't load, the checkboxes are still clickable.
<div class="fake-select">
<label for="fs1"><input type="checkbox" id="fs1" name="fs1" />Fake 1</label>
<label for="fs2"><input type="checkbox" id="fs2" name="fs2" />Fake 2</label>
[ ... ]
</div>
Basically, you need to track the user's keypresses and an "active" input. Look for up/down arrow key presses and change the active input based on that (scroll to it, add a class name for styling). I have it also allowing the space bar to check/uncheck the currently active box.
var fs = $(".fake-select"),
items = fs.find('input'),
divs = fs.find('label'),
active = 0;
// Hook keypresses
fs.keydown( function(e){
reCalculate(e);
rePosition();
return false;
});
// Click event for manual changes
items.unbind('click').click(function(e){
var thisInput = $(this),
thisLabel = $(this).parent();
window.active = thisLabel.index();
thisLabel.removeClass("checked");
if (thisInput.is(":checked"))
thisLabel.addClass("checked");
rePosition();
});
// Set new active element based on keypress
// Trigger click event if user hits space bar
function reCalculate(e){
var max = items.length -1,
cur = window.active,
charCode = (typeof e.which == "number" && e.which) ? e.which : e.keyCode;
if (charCode == 38) { // move up
cur--;
cur = (cur <= 0) ? 0 : cur;
}
if (charCode == 40) { // move down
cur++;
cur = (cur >= max) ? max : cur;
}
if (charCode == 32) { // space bar
items.eq(cur).focus().trigger('click');
}
window.active = cur;
}
// Add active class, call scroll function
function rePosition(){
divs.removeClass('active').eq(window.active).addClass('active');
scrollInView();
}
// Scroll the list so the active element is in view
function scrollInView(){
var target = divs.eq(window.active);
if (target.length) {
var top = fs.scrollTop() + target.position().top - fs.height()/2 + target.height()/2
fs.stop().animate({scrollTop: top}, 400);
}
return false;
}
jsFiddle example: http://jsfiddle.net/daCrosby/kqecngv0/13/
Can you use jQuery? This will activate the focus functionality via up/down arrow
function focusOnCheckboxes(locator){
var checkboxes = jQuery(locator).find(':checkbox');
var index = 0;
jQuery(locator).on('keydown', function(e){
if( e.keyCode == 38 ){
if(index > 0){
index = index - 1;
}
checkboxes[index].focus();
}
else if(e.keyCode == 40){
if(index < checkboxes.length - 1){
index = index + 1;
}
else{
index = checkboxes.length - 1;
}
checkboxes[index].focus();
}
else{
//console.log(e.keyCode);
}
});
}
// set the locator
focusOnCheckboxes('body');

HTML 5 Drag and Drop in correct position

I am trying to make a simple educational game for kids, where they will drag and drop pictures of planets and need to put them in the correct boxes in the correct order.
What I'm trying to figure out is the JS needed to let check the element being dropped on a box is the one that will match that box. The code I have so far allows me to drag and drop but has no check. Here is what I have:
<script type="text/javascript">
function allowDrop(ev){
ev.preventDefault();
}
function drag(ev){
ev.dataTransfer.setData("content", ev.target.id);
}
function drop(ev){
ev.preventDefault();
var image= ev.dataTransfer.getData("content");
ev.target.appendChild(document.getElementById(image));
}
</script>
<section id="planetbox">
<img id="mercuryImg" draggable="true" ondragstart="drag(event)" src="./images/planets/mercury.gif">
</section>
<section id="mercurybox"ondrop="drop(event)" ondragover="allowDrop(event)"> </section>
Any help would be really great. P.S. needs to use HTML 5, CSS and JS only no libraries :)
I managed to solve my issue using the code below on the function drop(ev):
function drop(ev){
ev.preventDefault();
var image= ev.dataTransfer.getData("content");
if ( image == ev.target.id) {
ev.target.appendChild(document.getElementById(image));
}
else {
}
}

Show div on image click then hide it after x seconds

I'm trying to show a div when an image is clicked and then hide it after a given number of seconds. I've found two separate code samples that match my needs but I don't have the knowledge to put them together.
the code which makes content disappear after x seconds:
<script>
window.setTimeout(function() {
$('#fadeout').hide(2000);
}, 4000);
</script>
The code which makes the div appear on imageclick:
<SCRIPT>
function fade(div_id, button) {
if(button.value == 'FadeOut') {
$('#'+div_id).fadeOut('slow');
button.value = 'FadeIn';
}
else {
$('#'+div_id).fadeIn('slow');
button.value = 'FadeOut';
}
}
$('#sometext').fadeOut(2);
</script>
Maybe this could help:
$('#fadeout').hide(); // hide div
$('img').live('click', function(e){
e.preventDefault(); //cancel default action of click
$('#fadeout').show().delay(5000).fadeOut(1000); //show div on img click then hide after 5 seconds
});
here's a working sample: http://jsfiddle.net/7X767/3/
Instead of using 'slow', you can use time value in milliseconds.