Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

ProgressBar Problems

edited August 2015 in Help! with 2.0
I want to include a progressbar in my Twine / Harlowe story.

I can include it in a web page by using a <div> like this:
<div id="progress-bar">&nbsp;</div>
However, including the Story JavaScript code & Story StyleSheet CSS doesn't work:

Story JavaScript:
function progress() {
var progressBar = $('#progress-bar'),
    width = 100;
progressBar.width(width + '%');
var interval = setInterval(function() {
    width -= 10;
    progressBar.css('width', width + '%');
    if (width <= 0) {
        clearInterval(interval);
    }
}, 1000) 
}
Story Stylesheet:
#progress-bar {
    width: 0;
    background: #f78;
    text-align: center;
    overflow: hidden; 
}

Here is a preview of how it should work: http://jsfiddle.net/94wKr/

I'm probably forgetting something simple, but any help would be appreciated. Thanks.

Comments

  • edited August 2015
    Issues:
    1. You're not arranging for your function to be called, so it never is. That's your main problem.
    2. Your code can potentially set a negative width, which you don't want to do.
    3. For intervals with finite lifespans you should clear the internal as soon as you know you need to do so. With the delay you're using here it's not an issue, however, with a minimal delay and lengthy workload, it's possible for additional, unwanted, callbacks to occur.
    4. Be consistent with your method calls. Use width([…]) or css("width", […]), not both. It wasn't hurting anything here, but it's bad form.

    Solutions:
    1. Use jQuery's document ready callback. IOW, wrap your function in $([…]) or the equivalent $(document).ready([…]). Normally, I do not advise using jQuery's document ready callback to trigger user code, since it's already in use by the story format, but I'm unsure what would be a better hook in Harlowe, so….
    2. Insure your decrement code cannot go below 0. Something like width = Math.max(0, width - 10) would work. For an incrementing progress bar, it would be something like width = Math.min(100, width + 10).
    3. Move the width check and clearInterval() call up to just after the width modification.
    4. Just be consistent.

    Try this:
    $(function progress() {
    	var	$bar  = $("#progress-bar"),
    		width = 100;
    	$bar.css("width", width + "%");
    
    	var intervalId = setInterval(function() {
    		width = Math.max(0, width - 10);
    		if (width === 0) {
    			clearInterval(intervalId);
    		}
    		$bar.css("width", width + "%");
    	}, 1000);
    });
    
    n.b. $bar is not a story variable. I find that prefixing jQuery-wrapped elements with the dollar sign is a nice convention.
  • Thank you for the quick reply.

    This works and I'm really grateful for you pointing out what I did wrong so I can learn from it.
Sign In or Register to comment.