Hype API - javascript change source image element

I’m quite new to Hype and doing Javascript but eager to learn. I’m trying to set the backgroundImage of a rectangle element or the source of an image element from an external JS file. I’ve tried so many things now in my 9 hour quest for the answer that I’m at a loss.

I’ve tried thing like:
HYPE.documents['myFile'].hypeDocument.getElementById('myElement').style.backgroundImage = "${resourcesFolderName}/myImage.jpg";

var template = document.getElementById('myElement');
if (template != undefined) {
template.attr("src", "${resourcesFolderName}/myImage.jpg");

or with
template.style.backgroundImage = "${resourcesFolderName}/myImage.jpg");

I commend your persistence for trying different things out!

The crux of the problem you’re hitting is that the ${resourcesFolderName} magic variable is a string substitution that Hype makes to its javascript functions/head html/inner html at export time. So if you have external javascript code (or even a .js file within the resources library), this string will not be replaced. Thus you’ll be setting the backgroundImage to literally something with the ${resourcesFolderName} string inside, which is not what you actually want. Instead you’ll need to either store this as a variable ahead of time from some code that Hype touches as it exports like a <script> section within the head HTML, or just give it the final export folder name yourself like documentname.hyperesources.

The other issue with your code is that the HYPE.documents['myFile'] returns a hypeDocument object itself, so you directly call API functions from there.

Working code would look more like:

HYPE.documents['myFile'].getElementById('myElement').style.backgroundImage = "myFile.hyperesources/myImage.jpg";

Thank you Jonathan,

You just made my day!
Although the style.background still doesn’t work I found a solution with your help :wink:
(left your code in the code below, but now commented out)

function dataInsert(data)   {
    for (var id in data) {
        var idTemplate = document.getElementById(id);
        if (idTemplate != undefined)   { 
            if (id == 'myElement') {
                idTemplate.innerHTML = "<img src='myFile.hyperesources/"+ escapeHtml(data[id]) +".jpg' width='93px' height='16px'/>";
                //HYPE.documents['myFile'].getElementById('myElement').style.backgroundImage = "myApp.hyperesources/"+escapeHtml(data[id])+".jpg";
            } else {
                idTemplate.innerHTML = escapeHtml(data[id]); 

Have a look at the extension project. That might help to get you started in generic aproaches that extend the API also to set the background use the setElementProperty function call (look at the function documentation in the Hype app)

1 Like