Saturday, May 21, 2011

HTML in AIR: Part 10

In today's tutorial we're going to learn more about reading and setting values of HTML content using Javascript and Actionscript.

From the previous tutorial we already know how to set and read text variables, but thanks to DOM, we can do much more than that. We can, for example, send references to more complicated objects like functions:

var myHtml:HTMLLoader = new HTMLLoader();
myHtml.width = 550;
myHtml.height = 400;
myHtml.load(new URLRequest("air_js.html"));
addChild(myHtml);
myHtml.addEventListener(Event.COMPLETE, onload);

function onload(Event):void
{
myHtml.window.showText = function(){
trace("hello");
};
}

Now when you click on the only button in our HTML page, it is going to trace "hello" in our Flash output window.

You can also call JS functions from AS3 using the window property:

function onload(Event):void
{
myHtml.window.alert("Page loaded!");
}

We can also get references to HTML objects with ids, but for the next example, we'll need to edit the HTML content a bit and add a paragraph object that we will later refer to.

<html>
<script type="text/javascript">
var mytext = "This is some text";
function showText(){
alert(mytext);
}
</script>
<body>
<input type="button" onclick="showText()" value="Alert"><br>
<p id="myp">Default paragraph text</p>
</body>
</html>

As you can see, the id of the p tag is set to myp. This means we can refer to it using this id through DOM.

We can find the paragraph by calling a getElementById() of the document and pass the id name as the parameter. We can then set its text by using the innerText property.

function onload(Event):void
{
myHtml.window.document.getElementById("myp").innerText="New text!";
}

Note that this only passes text. To pass some HTML, we can use the innerHTML property:

function onload(Event):void
{
myHtml.window.document.getElementById("myp").innerHTML="New text!";
}

Thanks for reading!

Related:

HTML in AIR: Part 1
HTML in AIR: Part 2
HTML in AIR: Part 3
HTML in AIR: Part 4
HTML in AIR: Part 5
HTML in AIR: Part 6
HTML in AIR: Part 7
HTML in AIR: Part 8
HTML in AIR: Part 9
HTML in AIR: Part 11
HTML in AIR: Part 12
HTML in AIR: Part 13
HTML in AIR: Part 14
HTML in AIR: Part 15
HTML in AIR: Part 16
HTML in AIR: Part 17

No comments:

Post a Comment