简体   繁体   中英

Jquery on button click do timer with progress-bar

So I was trying to make a little game but the first step just doesn't work. This is my code

<div id="box1">
        <button id="button">Click Me</button>
        <div id="progress-bar"></div>
    </div>

$('button').click(function() {
var progressBar = $('#progress-bar'),
width = 0;
progressBar.width(width);
var interval = setInterval(function () {
    width += 2.5;
    progressBar.css('width', width + '%');
    if (width >= 100) {
        clearInterval(interval);
    }
 }, 125)
});

#progress-bar {
width: 0;
background: red;
text-align: center;
overflow: hidden;   
height: 4px;
position: absolute;
bottom: 0px;
}
#box1 {
height: 100px;
width: 600px;
position: relative;
border: 1px solid grey;
}

So when clicking the button there will be a progress-bar at the bottom of box1. When doing a document ready it works but when using the .click it doesn't work.

When doing a document ready it works but when using the .click it doesn't work.

It works when you have a $(document).ready wrapped around your code because that instructs the javascript engine to wait until all js is fully loaded before trying to execute.

If you don't have the $(document).ready and you click before the everything is loaded, then you'll get a console error.

Press F12 to open developer toos and perform the same action, I would suspect you'll see an error in the console.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM