2

I have a problem when trying to get a picture from my static files, but from a javascript finction.

Here is my code for javascript:

<script type="text/javascript">
    var url_1 = '{% static "assets/img/stolovi/2.jpg" %}';

    function addimage1() {
        var img = document.createElement("img");
        img.src = url_1;
        img.height = 50;
        img.width = 50;
        img.draggable = true;
        //optionally set a css class on the image
        var class_name = "foo";
        img.setAttribute("class", class_name);

        document.getElementById("myDiagramDiv").appendChild(img);
        //document.body.appendChild(img);
        $(img).draggable({containment:'#myDiagramDiv'});
        }
</script>

How can I get that picture in my addimage1 function and set it as img.src?

My Script tag is inside a html tag, I don't know if that is important.

1 Answer 1

1

So for the most part your code is working just fine. I think you may have a problem with the library you are trying to use. Here is a similar working example.

https://jsfiddle.net/chrshawkes/4eaqpdsn/

<div id="myImage">

</div>

<script>
var url_1 = 'https://www.gravatar.com/avatar/1d42ea6e005a4160211f7b1957ce0a09/?default=&s=64';

function addimage1() {
  var img = document.createElement("img");
  img.src = url_1;
  img.height = 50;
  img.width = 50;
  //optionally set a css class on the image
  var class_name = "foo";
  img.setAttribute("class", class_name);

  document.getElementById("myImage").appendChild(img);
}

addimage1();
</script>
Sign up to request clarification or add additional context in comments.

5 Comments

Well yes, that works, but i want to get the picture from my static files.
are any of your static files working? do you have {% load staticfiles %} at the top of the template? If so, there is no reason you can't assign a javascript image variable using the django static way. var url_1 = '{% static "assets/img/stolovi/2.jpg" %}'; I would check and see what url is being returned by that static keyword and see if there is a 404 file not found error
yes, all of them are working just fine, but this one wont.
are you getting a 404, have you checked the console to see if there is a javascript error occurring?
Yes i was getting a 404, thank you, I didn't know where to look, solved it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.