Monkey X can use native functions from within monkey code. This article will focus on the Html5 target. Although the principles apply to other targets as well.

When targeting Html5 you practically get the all the JavaScript functions your browser supports for free. You don’t have to stop there though. Why not use jQuery? Or any other JS framework, then wire it up to monkey. This allows you to draw buttons, checkboxes and any other <div> above your game.

In this article we will display an <h1> tag in your game:
We will create 2 files: native.js and native.monkey
They will need to be in the same folder for this example.

native.monkey

Strict
#If TARGET = "html5"
	Import "native.js"

    Extern
    Function HtmlAdd:Void(markup:String)
    Function HtmlSet:Void(id:String, value:String)
#End

First the native functions are imported. Next 2 functions are defines as Extern, meaning monkey will look for the implementation in the native file.

native.js

function HtmlAdd(markup) {
  var parser = new DOMParser();
  var doc = parser.parseFromString(markup, "text/html").documentElement;
	var element = doc.childNodes[1].childNodes[0];
	document.body.appendChild(element);
}

function HtmlSet(id, value) {
	var element = document.getElementById(id);
	if (element) {
		element.innerHTML = value;
	}
}

This is the native implementation. Note that the function names are exactly the same as in the monkey file.

And finally how to use it on the client side:

Strict
Import mojo
Import native 'imports the monkey file

Class MyApp Extends App
    Method OnCreate:Int()
        Local css:String = "color: red; letter-spacing: 0.5em; position: absolute;"
        css += "z-index: 1; top: 20px; left: 20px;"
        Local markup:String = "<h1 id='heading' style='" + css + "'></h1>"
        HtmlAdd(markup)
        Return 0
    End

    Method OnUpdate:Int()
        HtmlSet("heading", Millisecs()) 'heading is the id
        Return 0
    End

    Method OnRender:Int()
        Cls()
        DrawCircle(50, 50, 50)
        Return 0
    End
End

Function Main:Int()
    New MyApp
    Return 0
End

Monkey X displaying html tag h1 above the canvas

The result shows the <h1> above the canvas. Also note that using ids in this example was arbitrary. The way you communicate between monkey and native code is up to you.

Bonus Knowledge

The native function names can actually differ from the monkey ones. All you have to do is then tell monkey the name of the native function. Consider that we defined our HtmlSet function in native.js as htmlSetValue. This is how you wire things up in native.monkey:

Strict
#If TARGET = "html5"
	Import "native.js"

    Extern
    Function HtmlAdd:Void(markup:String)
    Function HtmlSet:Void(id:String, value:String) = "htmlSetValue"
#End