Howdy, Stranger!

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

How to invoke a Javascript function with a button in Sugarcube?

What I'm trying to do is to invoke a Javascript function that (I think) I defined in the global story javascript. Here's what I did:

1. Wrote my "test" passage:
<div id="progressbar-container"><div id="progressbar"></div></div>

2. Set up the CSS in the Story CSS:
#progressbar-container {
	width: 12em;
        background-color: transparent;
	border: 1px solid white;
	border-radius: 4px;	
}

#progressbar {
	  width: 0%;
          height: 2em;
          background-color: green;
          border-radius: 4px;
}

3. Chucked the following code into the Story Javascript:
function move() {
    var elem = document.getElementById("progressbar"); 
    var width = 1;
    var id = setInterval(frame, 100);
    function frame() {
        if (width >= 100) { clearInterval(id); } 
        else {
            width++; 
            elem.style.width = width + '%'; 
        }
    }
}

4. And finally, I referred to this thread: https://twinery.org/forum/discussion/6524/calling-js-functions-in-twine-2-sugarcube-without-macros-is-it-possible and I put a button that attempts to invoke the "move()" function into the passage:
<<button "Test">><<script>>move();<</script>><</button>>
But when I click the button, get an error message that says bad evaluation: move is not defined.

Please forgive my rather elementary understanding of how Javascript works XD

Comments

  • Your function is not global, it's contained within its own scope which isn't accessible by SugarCube.

    You either need to make it an auto-global, by making it a static method of the window object, or make it a static method of SugarCube's setup object. If you choose the former, you must be careful as the window object contains various APIs which you do not want to clobber.

    On the window object
    Add the following to your Story JavaScript:
    window.move = function () {
    	var elem  = document.getElementById("progressbar");
    	var width = 1;
    	var id    = setInterval(frame, 100);
    
    	function frame() {
    		if (width >= 100) {
    			clearInterval(id);
    		}
    		else {
    			width++;
    			elem.style.width = width + '%';
    		}
    	}
    };
    
    Usage:
    <<button "Test">><<script>>move();<</script>><</button>>
    


    On SugarCube's setup object
    Add the following to your Story JavaScript:
    setup.move = function () {
    	var elem  = document.getElementById("progressbar");
    	var width = 1;
    	var id    = setInterval(frame, 100);
    
    	function frame() {
    		if (width >= 100) {
    			clearInterval(id);
    		}
    		else {
    			width++;
    			elem.style.width = width + '%';
    		}
    	}
    };
    
    Usage:
    <<button "Test">><<script>>setup.move();<</script>><</button>>
    
  • As always, you're awesome, TME. Thank you :D
Sign In or Register to comment.