0 votes
by (140 points)
This is my javascrpit code, whIn i run the code, the link always appears in one place, can any help me figure out why? Thanks, I need it ASAP.

function getRandomPosition(element) {
    var x = document.body.offsetHeight-element.clientHeight;
    var y = document.body.offsetWidth-element.clientWidth;
    var randomX = State.floor(State.random()*x);
    var randomY = State.floor(State.random()*y);
    return [randomX,randomY];
}
window.onload = function() {
    var link = document.createElement('aBlock');
    link.setAttribute("style", "position:absolute;");
    document.body.appendChild(link);
    var xy = getRandomPosition(link);
    link.style.top = xy[0] + 'px';
    link.style.left = xy[1] + 'px';
}

2 Answers

0 votes
by (68.6k points)

There's no such method State.floor(), which is likely your chief problem.  You want Math.floor().

0 votes
by (159k points)

Based on TheMadExile's answer, one way to get your Javascript code example to work would be to do the following.

1. Define your getRandomPosition() function on the special setup object within you're project's Story Javascript area.

setup.getRandomPosition = function (element) {
    var x = document.body.offsetHeight - element.clientHeight;
    var y = document.body.offsetWidth - element.clientWidth;
    var randomX = Math.floor(State.random() * x);
    var randomY = Math.floor(State.random() * y);
    return [randomX, randomY];
};

2. Call the `setup.getRandomPosition()` function within the current Passage using a <<script>> macro combined with a either a Passage Events or a Task Objects. The following example uses the jQuery one() function to listen for the :passagedisplay event, this allows the content of the current Passage to be rendered before the custom 'aBlock' element is created and positioned.

<<script>>
	$(document).one(':passagedisplay', function (ev) {
		var link = document.createElement('aBlock');
		link.setAttribute("style", "position:absolute;");

		document.body.appendChild(link);
		var xy = setup.getRandomPosition(link);
		link.style.top = xy[0] + 'px';
		link.style.left = xy[1] + 'px';
	});
<</script>>

WARNING: Because the position of the above 'aBlock' element can be anywhere within the current viewport of the web-browser it is possible that it will appear behind the (Left) UIBar, you may want to limit the area that the 'aBlock' element can appear within to that defined by the .passage classed element.

...