JavaScript progress bar - javascript

I want to have a progress bar which should show when I click on a button, e.g. "validate now". My requirement is to check 2000 URLs whether they are working or not. This was taking a lot of time while executing in program. So I need to show a progress bar to the user to know the status. How can I do this using JavaScript?

you could use the jQuery UI Progress bar simple, good looking and easy to implement, you just need to update the value every second or two.
$("#progressbar").progressbar({
value: 37
});

You would have to use Ajax and hit the server/ database every 2-3 second and fetch the status and display on web page. To display progress bar you can use table with different tds and set the background color of these td cells with the status result.
For progress bar create a table with 10 cells of equal width and say the status is 40% then you will set background of first 4 cells indicating 40%.

You could use ProgressBar.js. No dependencies, easy API and supports major browsers.
var line = new ProgressBar.Line('#container');
line.animate(1);
See more examples of usage in the demo page.

Pure JavaScript is not possible, you need to use Ajax to get the current status which requires Server-Side Scripting (I guess PHP in your case).
Store the total and completed URLs (or their counts) in the database or in a session and use get the percentage of completed URLs from there in PHP, called by a JavaScript Ajax request. Then give the percentage to the jQuery bar as Prutswonder suggested in another answer.
I suggest using JSON or simply Plaintext to receive the Data in JavaScript, XML would be unneccessary overhead (so it's actually AJAJ or AJAP, not Ajax).

I found a pop up Javascript bar. Might need some modifications to fit what you have in mind, but looks promising.
code is
<style>
<!--
.hide { position:absolute; visibility:hidden; }
.show { position:absolute; visibility:visible; }
-->
</style>
<SCRIPT LANGUAGE="JavaScript">
//Progress Bar script- by Todd King (tking#igpp.ucla.edu)
//Modified by JavaScript Kit for NS6, ability to specify duration
//Visit JavaScript Kit (http://javascriptkit.com) for script
var duration=3 // Specify duration of progress bar in seconds
var _progressWidth = 50; // Display width of progress bar.
var _progressBar = "|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||"
var _progressEnd = 5;
var _progressAt = 0;
// Create and display the progress dialog.
// end: The number of steps to completion
function ProgressCreate(end) {
// Initialize state variables
_progressEnd = end;
_progressAt = 0;
// Move layer to center of window to show
if (document.all) { // Internet Explorer
progress.className = 'show';
progress.style.left = (document.body.clientWidth/2) - (progress.offsetWidth/2);
progress.style.top = document.body.scrollTop+(document.body.clientHeight/2) - (progress.offsetHeight/2);
} else if (document.layers) { // Netscape
document.progress.visibility = true;
document.progress.left = (window.innerWidth/2) - 100+"px";
document.progress.top = pageYOffset+(window.innerHeight/2) - 40+"px";
} else if (document.getElementById) { // Netscape 6+
document.getElementById("progress").className = 'show';
document.getElementById("progress").style.left = (window.innerWidth/2)- 100+"px";
document.getElementById("progress").style.top = pageYOffset+(window.innerHeight/2) - 40+"px";
}
ProgressUpdate(); // Initialize bar
}
// Hide the progress layer
function ProgressDestroy() {
// Move off screen to hide
if (document.all) { // Internet Explorer
progress.className = 'hide';
} else if (document.layers) { // Netscape
document.progress.visibility = false;
} else if (document.getElementById) { // Netscape 6+
document.getElementById("progress").className = 'hide';
}
}
// Increment the progress dialog one step
function ProgressStepIt() {
_progressAt++;
if(_progressAt > _progressEnd) _progressAt = _progressAt % _progressEnd;
ProgressUpdate();
}
// Update the progress dialog with the current state
function ProgressUpdate() {
var n = (_progressWidth / _progressEnd) * _progressAt;
if (document.all) { // Internet Explorer
var bar = dialog.bar;
} else if (document.layers) { // Netscape
var bar = document.layers["progress"].document.forms["dialog"].bar;
n = n * 0.55; // characters are larger
} else if (document.getElementById){
var bar=document.getElementById("bar")
}
var temp = _progressBar.substring(0, n);
bar.value = temp;
}
// Demonstrate a use of the progress dialog.
function Demo() {
ProgressCreate(10);
window.setTimeout("Click()", 100);
}
function Click() {
if(_progressAt >= _progressEnd) {
ProgressDestroy();
return;
}
ProgressStepIt();
window.setTimeout("Click()", (duration-1)*1000/10);
}
function CallJS(jsStr) { //v2.0
return eval(jsStr)
}
</script>
<SCRIPT LANGUAGE="JavaScript">
// Create layer for progress dialog
document.write("<span id=\"progress\" class=\"hide\">");
document.write("<FORM name=dialog id=dialog>");
document.write("<TABLE border=2 bgcolor=\"#FFFFCC\">");
document.write("<TR><TD ALIGN=\"center\">");
document.write("Progress<BR>");
document.write("<input type=text name=\"bar\" id=\"bar\" size=\"" + _progressWidth/2 + "\"");
if(document.all||document.getElementById) // Microsoft, NS6
document.write(" bar.style=\"color:navy;\">");
else // Netscape
document.write(">");
document.write("</TD></TR>");
document.write("</TABLE>");
document.write("</FORM>");
document.write("</span>");
ProgressDestroy(); // Hides
</script>
<form name="form1" method="post">
<center>
<input type="button" name="Demo" value="Display progress" onClick="CallJS('Demo()')">
</center>
</form>
Text link example
<p align="center">This free script provided by<br />
<a href="http://www.javascriptkit.com">JavaScript
Kit</a></p>
found here code

You can make the progress bar by increasing the div width at some interval of time.
For example, you may increase the 1px width of div at each 50 milliseconds like,
var width = 1
function render (){
if(width <=100){
// apply width to div for progress bar
div.style.width = width + "px";
setTimeout(
function (){
render();
width++;
},50
);
}
}
render();

Related

How do I hide a div or image after 20 seconds of flashing in Javascript?

I am busy making a memory game, where an image is to be displayed to the user, and after some 10 seconds of the image flashing, it should hide and four options are to be shown for the user to choose either the correct or incorrect answer.
So far, all I have accomplished is to load the images and cycle through all the puzzles that my code can find.
What I'm trying to do now is to make the image flash and hide after some time, while also just refreshing that section of the page, and not the entire page.
I am using C# and a user control on my page.
What I have tried so far is only
<script>
var x;
function BlinkImage() {
x = 1;
setInterval(change, 2000);
}
function change() {
if (x === 1) {
var image = document.getElementById('<%=imgMain.ClientID %>');
image.visible = false;
x = 2;
}
else {
var image = document.getElementById('<%=imgMain.ClientID %>');
image.visible = true;
x = 1;
}
}
</script>
And on loading my puzzle for that instance (in code behind)
Page.ClientScript.RegisterStartupScript(typeof(game), "Start", "<script language=javascript> BlinkImage(); </script>");
Which does fire, as I can step through the code in debugging on Firefox. But my image does not flash or blink. I understand I am just using visiblity as my "blinker". I don't know what else to use exactly.
What can I do to make the image flash or blink for, say 20 seconds, then hide the image after that time has passed? Then repeat the process once the user has made a choice.
You can try the following (comments in code):
var blinkInterval = setInterval(change, 2000), // set the interval into a variable
image = document.getElementById('test'), // replace test with your client id: <%=imgMain.ClientID %>
x = 1;
function change() {
if (x % 2 === 1) { // see if it is odd or even by modding by 2 and getting remainder
image.style.display = 'none';
} else {
image.style.display = 'block';
}
x++; // increment x
if (x === 10) { // should have happened 10 times (which is 20 seconds with your intervals being at 2 seconds)
clearInterval(blinkInterval); // clear the interval (should end hidden as odd is display none and we clear beforethe 20th is run)
}
}
<div id="test">test</div>
After the code has finished, wherever the user is making their selection, you just need to reset the blinkInterval variable:
blinkInterval = setInterval(change, 2000); // notice no need for the var declaration when you reset this
Use style attribute and change if visible/hidden
function change() {
var image = document.getElementById('<%=imgMain.ClientID %>');
//check if visible
if (image.style.visibility=="visible") {
image.style.visibility="hidden";
}
else {
image.style.visibility="visible";
}
}
;
Try this:
function flashAndHide(img_id){
var img = $("#"+img_id);
var x = 0;
var inter = setInterval(function(){
if(x % 2 == 0){
img.hide();
}else{
img.show();
}
x += 1;
}
},1000);
if(x === 20){
img.hide();
clearInterval(inter);
}
}
Haven't tested this, but it should work,

How to make a text slider that moves next or previous in javascript?

Ok so I've revised the markup/code to make it easier to understand. Using JavaScript I want to know how to create a text slider that changes a paragraph in html5 either "forwards" or "backwards" on click?
I only want one div to show at a time and the first div (div_1) needs to be visible at the beginning as a default setting. I also want to be able to add more text divs to it in the future. I'm new to JavaScript so I want to keep it as simple as possible.
I've had a go creating it in JavaScript which hasn't worked, I'm not sure if I'm going about this the right way.
<!DOCTYPE html>
<html lang="en">
<head>
<style type="text/css">
.showHide {
display: none;
}
</style>
<script type="text/javascript">
var sdivs = [document.getElementById("div_1"),
document.getElementById("div_2"),
document.getElementById("div_3"),
document.getElementById("div_4")];
function openDiv(x) {
//I need to keep div_1 open as a starting point
sdivs[0].style.display ="block";
var j;
for (var j = 0; j < sdivs.length; j++) {
if (j === x) {
continue;
}
else {
sdivs[j].style.display = "none";
}
}
}
</script>
<title>text</title>
</head>
<body>
forward
backwards
<div id="text_holder">
<div id="div_1" class="showHide">One</div>
<div id="div_2" class="showHide">Two</div>
<div id="div_3" class="showHide">Three</div>
<div id="div_4" class="showHide">Four</div>
</div>
</body>
</html>
When dealing with multiple elements like this, I've found CSS alone to be insufficient (though its brilliant for modifying simple hover states or whatever). This one method here is pretty simple and specific to this one set of markup (so modify as you see fit). More importantly - its to illustrate how to set up a simple javascript "class" to handle your logic.
http://jsfiddle.net/1z13qb58/
// use a module format to keep the DOM tidy
(function($){
// define vars
var _container;
var _blurbs;
var _blurbWidth;
var _index;
var _clicks;
// initialize app
function init(){
console.log('init');
// initialize vars
_container = $('#text_holder .inner');
_blurbs = $('.blurb');
_blurbWidth = $(_blurbs[0]).innerWidth();
_clicks = $('.clicks');
_index = 0;
// assign handlers and start
styles();
addEventHandlers();
}
// initialize styles
function styles(){
_container.width(_blurbs.length * _blurbWidth);
}
// catch user interaction
function addEventHandlers(){
_clicks.on({
'click': function(el, args){
captureClicks( $(this).attr('id') );
}
});
}
// iterate _index based on click term
function captureClicks(term){
switch(term){
case 'forwards':
_index++;
if(_index > _blurbs.length - 1){
_index = 0;
}
break;
case 'backwards':
_index--;
if(_index < 0){
_index = _blurbs.length - 1;
}
break;
}
updateView();
}
// update the _container elements left value
function updateView(){
//_container.animate({
//'left' : (_index * _blurbWidth) * -1
//}, 500);
_container.css('left', ((_index * _blurbWidth) * -1) + 'px');
}
init();
})(jQuery);
I'm using jQuery to handle event binding and animation, but, again - there are lots of options (including a combination of vanilla javascript and CSS3 transitions).
I'll note also that this is all html4 and css2 (save your doctype).
Hopefully that helps -

JavaScript page resizing

I know that you don't normally like doing things like this but I'm at University and have to do a project with several different stylesheets for the same page. I have been given JavaScript code to enable me to resize the page when the window is resized.
This code works however I am getting a peculiar effect on one of the stylesheets where the content div takes up most of the page when it shouldn't, this page has measurements in ems whereas my other stylesheets use px but I am supposed to use ems for at least one page. Although I could give my lecturer a reason for it being bigger I would prefer to fix the problem. The JavaScript code I am using is shown below:
function smoothresize() {
blockwidth = 59.4; /*This is in ems as per the lecturers request a well and is the size of the container div I created*/
minmargin = 0;
minsize = 10;
emwidth = (minmargin * 2) + blockwidth;
computeResize(emwidth, minsize, false)
}
function computeResize(wide, minsize, jerk) {
windowpixels = document.documentElement.clientWidth;
pixelsize = windowpixels / wide;
emsize = calculateEmsize(pixelsize, minsize, jerk);
b = document.getElementsByTagName('html')[0];
b.style.fontSize = emsize + "em";
}
function calculateEmsize(psize, minsize, jerk) {
if (psize > minsize) {
raw = psize;
}
else {
raw = minsize;
}
if (jerk) {
result = ((Math.floor(raw)) / 16);
}
else {
result = raw / 16;
}
return result
}
This is where I have Implemented the code in my XHTML:
<body onload="smoothresize()" onresize="smoothresize()">
I wouldn't be able to use jQuery as a solution to the problem either, I would only be able to modify the code given.
Any help in this matter Would be greatly appreciated
Check out jQuery's user interface plugin. It contains a "resizable" option; you ought to be able to add <script type="text/javascript">window.onload=function(){};</script> that loads the desired JQUI function upon page load.

HTML javascript bookmark user viewing position

I have a html webpage. It contains a very long text passage.
User can use internet browser to read the passage. Since the passage is long, users need to scroll the page to read the whole passage.
I would like to add a floating box button for user to click. After clicking the button, I can capture the current viewing portion of the passage.
So that users can log in later and continue reading.
I think I need to add some javascript, but after hours of online searching, I failed to find relevant information.
Please kindly suggest the possible solution to do so?
Use a position:fixed box/button. Clicking it stores (or updates, if it already exists) a localStorage item or cookie with the current position. On page load, if that item exists, ask the user if they want to return to that spot.
There are two ways of doing this:
Save position as a pixel value. This works perfectly if the user's display will not change size (switching computers, switching monitors, changing screen resolution setting, etc.). However, if any of those changes do occur, the absolute pixel value of the saved position is not consistent with the position on the page.
Demo. To run: click "Save position", scroll anywhere, then reload the page.
Save position as a percentage of total height. This works exactly as solution (1), but handles all cases in which screen size changes as well. (Use this one.) The code provided below pertains to this solution.
Demo. To run: click "Save position"; change the width of the "Result" quadrant; without changing any code, click "Run" again.
The saved item is removed regardless of the user's choice (to return to the last spot or not), so that the prompt doesn't show up every time the page is reloaded (which can get annoying).
This is pure JS; it's very modular; it demonstrates simple usage of localStorage and falls back gracefully to cookies.
HTML
<div id="save">
<button id="saveButton">Save position</button>
<span id="saved">Saved!</span>
</div>
<div id="content">
<!-- Disgustingly long content -->
</div>
CSS
#save {
position:fixed;
top:30px;
left:10px;
width:20%;
}
#saved {
visibility:hidden;
color:green;
}
#content {
width:60%;
margin:auto;
}
JS
function checkStorageSupport() {
var test = "test";
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
return false;
}
}
function getTotalHeight() {
return document.body.clientHeight;
}
function getSavedPercent() {
var percent = storageSupported ? loadFromStorage() : loadFromCookie();
return (percent == null || percent == "") ? 0 : percent;
}
/******* Save *******/
function saveInStorage() {
localStorage.setItem("scrollPercent", (document.documentElement.scrollTop / getTotalHeight()));
}
function saveCookie() {
var expDate = new Date();
expDate.setDate(expDate.getDate() + 7); // start over if it's been more than ___ days
document.cookie = "scrollPercent=" + (document.documentElement.scrollTop / getTotalHeight())
+ "; " + expDate;
}
/******* Load *******/
function loadFromStorage() {
return localStorage.getItem("scrollPercent");
}
function loadFromCookie() {
return document.cookie.replace(/(?:(?:^|.*;\s*)scrollPercent\s*\=\s*([^;]*).*$)|^.*$/, "$1");
}
/******* Remove *******/
function removeFromStorage() {
localStorage.removeItem("scrollPercent");
}
function removeCookie() {
document.cookie = "scrollPercent=''";
}
/******* Handler *******/
var saveButton = document.getElementById("saveButton"),
saved = document.getElementById("saved");
saveButton.onclick = function() {
storageSupported ? saveInStorage() : saveCookie();
saved.style.visibility = "visible";
setTimeout(function() {
saved.style.visibility = "hidden";
}, 1500);
};
/******* Logic *******/
var storageSupported = checkStorageSupport(),
percent = getSavedPercent();
if (percent > 0) {
if (confirm("Would you like to continue reading where you left off?")) {
document.documentElement.scrollTop = percent * getTotalHeight();
}
storageSupported ? removeFromStorage() : removeCookie();
}
Note: to get back to the code that produces solution (1), copy the code from that demo. In the case JSFiddle goes down, here are manual instructions:
Remove every instance of / getTotalHeight() in a "Save" function
In the "Logic" section, replace position * getTotalHeight() with position
Remove getTotalHeight(), since it's not used
Replace instances of "percent" with "position" to be more semantically accurate
Basic idea is..
create a floating bookmark button on the page like:
#mybookmark{
position: fixed;
top:30px;
right:0;
}
Now in jquery.. retrieve the position of this floating bookmark when clicked on it..
$('#mybookmark').click(function(){
var bookmark_loc = $('#mybookmark').offset().top();
});
Store this bookmark_loc data in your preferred storage for the user.
then when they clicks on a button, you can scroll to the stored offset value in your storage.. in jquery
$('#scroll_to_bookmark').click(function{
var bookmark_loc = //Fetch bookmark
$('body').animate({ scrollTop: bookmark_loc; });
});

How to improve image cross-fade performance?

I want to be able to do a cross fade transition on large images whose width is set to 100% of the screen. I have a working example of what I want to accomplish. However, when I test it out on various browsers and various computers I don't get a buttery-smooth transition everywhere.
See demo on jsFiddle: http://jsfiddle.net/vrD2C/
See on Amazon S3: http://imagefader.s3.amazonaws.com/index.htm
I want to know how to improve the performance. Here's the function that actually does the image swap:
function swapImage(oldImg, newImg) {
newImg.css({
"display": "block",
"z-index": 2,
"opacity": 0
})
.removeClass("shadow")
.animate({ "opacity": 1 }, 500, function () {
if (oldImg) {
oldImg.hide();
}
newImg.addClass("shadow").css("z-index", 1);
});
}
Is using jQuery animate() to change the opacity a bad way to go?
You might want to look into CSS3 Transitions, as the browser might be able to optimize that better than Javascript directly setting the attributes in a loop. This seems to be a pretty good start for it:
http://robertnyman.com/2010/04/27/using-css3-transitions-to-create-rich-effects/
I'm not sure if this will help optimize your performance as I am currently using IE9 on an amped up machine and even if I put the browser into IE7 or 8 document mode, the JavaScript doesn't falter with your current code. However, you might consider making the following optimizations to the code.
Unclutter the contents of the main photo stage by placing all your photos in a hidden container you could give an id of "queue" or something similar, making the DOM do the work of storing and ordering the images you are not currently displaying for you. This will also leave the browser only working with two visible images at any given time, giving it less to consider as far as stacking context, positioning, and so on.
Rewrite the code to use an event trigger and bind the fade-in handling to the event, calling the first image in the queue's event once the current transition is complete. I find this method is more well-behaved for cycling animation than some timeout-managed scripts. An example of how to do this follows:
// Bind a custom event to each image called "transition"
$("#queue img").bind("transition", function() {
$(this)
// Hide the image
.hide()
// Move it to the visible stage
.appendTo("#photos")
// Delay the upcoming animation by the desired value
.delay(2500)
// Slowly fade the image in
.fadeIn("slow", function() {
// Animation callback
$(this)
// Add a shadow class to this image
.addClass("shadow")
// Select the replaced image
.siblings("img")
// Remove its shadow class
.removeClass("shadow")
// Move it to the back of the image queue container
.appendTo("#queue");
// Trigger the transition event on the next image in the queue
$("#queue img:first").trigger("transition");
});
}).first().addClass("shadow").trigger("transition"); // Fire the initial event
Try this working demo in your problem browsers and let me know if the performance is still poor.
I had the same problem too. I just preloaded my images and the transitions became smooth again.
The point is that IE is not W3C compliant, but +1 with ctcherry as using css is the most efficient way for smooth transitions.
Then there are the javascript coded solutions, either using js straight (but need some efforts are needed to comply with W3C Vs browsers), or using libs like JQuery or Mootools.
Here is a good javascript coded example (See demo online) compliant to your needs :
var Fondu = function(classe_img){
this.classe_img = classe_img;
this.courant = 0;
this.coeff = 100;
this.collection = this.getImages();
this.collection[0].style.zIndex = 100;
this.total = this.collection.length - 1;
this.encours = false;
}
Fondu.prototype.getImages = function(){
var tmp = [];
if(document.getElementsByClassName){
tmp = document.getElementsByClassName(this.classe_img);
}
else{
var i=0;
while(document.getElementsByTagName('*')[i]){
if(document.getElementsByTagName('*')[i].className.indexOf(this.classe_img) > -1){
tmp.push(document.getElementsByTagName('*')[i]);
}
i++;
}
}
var j=tmp.length;
while(j--){
if(tmp[j].filters){
tmp[j].style.width = tmp[j].style.width || tmp[j].offsetWidth+'px';
tmp[j].style.filter = 'alpha(opacity=100)';
tmp[j].opaque = tmp[j].filters[0];
this.coeff = 1;
}
else{
tmp[j].opaque = tmp[j].style;
}
}
return tmp;
}
Fondu.prototype.change = function(sens){
if(this.encours){
return false;
}
var prevObj = this.collection[this.courant];
this.encours = true;
if(sens){
this.courant++;
if(this.courant>this.total){
this.courant = 0;
}
}
else{
this.courant--;
if(this.courant<0){
this.courant = this.total;
}
}
var nextObj = this.collection[this.courant];
nextObj.style.zIndex = 50;
var tmpOp = 100;
var that = this;
var timer = setInterval(function(){
if(tmpOp<0){
clearInterval(timer);
timer = null;
prevObj.opaque.opacity = 0;
nextObj.style.zIndex = 100;
prevObj.style.zIndex = 0;
prevObj.opaque.opacity = 100 / that.coeff;
that.encours = false;
}
else{
prevObj.opaque.opacity = tmpOp / that.coeff;
tmpOp -= 5;
}
}, 25);
}

Categories