jQuery addClass example
Change class name on click in jQuery
by Andreas Strauman
HTML
<div id="banner-message">
<p>Progress:<span id="percentage">0%</span></p>
<button>Do progress!</button><br/>
<div id="progress"></div>
</div>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#progress {
margin-top: 1em;
background: #090;
width: 0%;
height: 1em;
}
#banner-message {
background: #fff;
border-radius: 4px;
padding: 20px;
font-size: 25px;
text-align: center;
transition: all 0.2s;
margin: 0 auto;
width: 300px;
}
button {
background: #0084ff;
border: none;
border-radius: 5px;
padding: 8px 14px;
font-size: 15px;
color: #fff;
}
#banner-message.alt {
background: #0084ff;
color: #fff;
margin-top: 40px;
width: 200px;
}
#banner-message.alt button {
background: #fff;
color: #000;
}
JavaScript
// find elements
var number_of_files_completed;
var number_of_files_to_upload = 0;
var progress_bar_percentage = 0;
var button = $("button")
// Using percentage instead of window width here
function prepare_progressbar(number_of_files) {
var max_progressbar_width = $(window).width();
// Reset the completed-counter
number_of_files_completed = 0;
// Set the global number of files
number_of_files_to_upload = number_of_files;
// Make progress bar "hidden"
$("#progress").css({
width: "0%"
});
}
function update_progressbar() {
number_of_files_completed += 1;
progress_bar_percentage = 100 * number_of_files_completed / number_of_files_to_upload;
$("#progress").css({
"width": progress_bar_percentage + "%"
});
$("#percentage").text(Math.round(progress_bar_percentage) + "%");
return progress_bar_percentage;
}
function pretend_to_upload() {
$.ajax({
url: "/echo/json/",
complete: update_progressbar,
dataType: 'json'
});
if (progress_bar_percentage <= 99) {
window.setTimeout(pretend_to_upload, 1000);
}
}
// Button click: update progress
button.on("click", function() {
prepare_progressbar(13);
pretend_to_upload();
})