Auto refresh picture withoud reloading page

Hi there,

I’m working on my first personal app using phoenix. I created a custom input helper which takes an image url from a textbox and displays it in an img_tag. I want this custom control to refresh image automatically when url changes. The problem is I don’t know how to do it. :frowning: What is the best way?

Here is my custom input:

defmodule DbuniverseWeb.InputHelpers do

use Phoenix.HTML

def image_url_input(form, field, label) do
    
    type = Phoenix.HTML.Form.input_type(form, field)
    
    wrapper_opts = [class: "form-group"]
    label_opts = [class: "control-label"]
    input_opts = [class: "form-control"]

    content_tag :div, wrapper_opts do

        label = label(form, field, label, label_opts)
        input = apply(Phoenix.HTML.Form, type, [form, field, input_opts])
        IO.inspect field
        img = img_tag(form.params["image_url"])
        
        [label, input, img]

    end
    

end

Thanks for your help!
Didier

2 Likes

So, to refresh it automatically on the client as the client changes it? That’s just javascript callbacks if so. Or are you wanting the server to process it and send back a ‘fixed up’ url, if so then something like unpoly.js would do that with ease on the client too. ^.^

2 Likes

I want it to be refreshed automatically on the client as the client changes it. The problem is that I don’t know how to define events with html tags… With this :

input = apply(Phoenix.HTML.Form, type, [form, field, input_opts])

How do you set the keyup event for example?

1 Like

Heh, not from the phoenix side. ^.^

Just give your ‘url’ input a unique ID, and the <img> tag a unique ID, then wire them up in your app.js or in a script tag (any normal html/javascript way, this has nothing to do with phoenix ^.^) with something like (syntax may not be accurate, but the gist of it is accurate):

// Do this in your document on-load event, or put it at the bottom of the html somehow
var inp = document.getElementById("my-input");
var img = document.getElementById("my-img-output");
inp.on_blur(event => {img.src = inp.value});

I’m really sure I have the some of that wrong, but my UI is not easy to use right now, but hopefully that gets you on the right path! ^.^

2 Likes

Ok thanks! What I’ve missed is how to set an id for my img tag. I simply added :

img_opts = [id: “img-url”]

and passed it as an argument when I invoke img_tag :

img = img_tag(form.params[“image_url”], img_opts)

2 Likes