This is less about Julia and more about JavaScript

When working within the IJulia interface, we often need to write JavaScript that will manipulate nodes that we've created in the past. Using the display method and some creative JavaScript, we can achieve this in a way that persists.

1. Create an id for the display node


In [2]:
displayid = "demo-node-" * string(rand())


Out[2]:
"demo-node-0.09351622817787297"

2. Create a node with that id


In [3]:
display(
    "text/html", 
    """<p id="$(displayid)" style="background-color:red; color:white; padding: 5px;">nothing here</p>"""
)


nothing here

3. Create a JavaScript function named with that ID

Note that this would be illegal in pure JavaScript, but we can do it by treating the function name as a property of the window object. This sort of also ensures that we do not collide with existing JavaScript functions.


In [3]:
display("text/html", """
<script>
    window["$(displayid)"] = function(text) {
        var p = document.getElementById("$(displayid)");
        if(p) {
            p.innerText = text;
        }
    };
</script>
""")


4. Later in our code we can update that node using its ID


In [4]:
display("text/html", """<script>window["$(displayid)"]("hello, world");</script>""")


This technique can be used when interacting with D3

We often run D3 visualisations within an iframe, and this method allows us to have multiple copies of the same viz without having data go to the wrong one.


In [ ]: