Steps for displaying an image from a static file using JavaScript in a Django project

Having an issue retrieving a picture from my static files using a JavaScript function.

Here is the JavaScript code in question:

<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 successfully fetch the picture in my addimage1 function and assign it to img.src?

My script tag is embedded inside an HTML element, unsure if that's relevant information.

Answer №1

It seems like your code is functioning properly for the most part. However, there may be an issue with the library you are attempting to utilize. To help you out, here is a similar example that is working smoothly:

Check out this demo

<div id="myImage">

</div>

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

function addImage() {
  var imageElement = document.createElement("img");
  imageElement.src = imageUrl;
  imageElement.height = 50;
  imageElement.width = 50;
  
  // You can also assign a CSS class to the image if needed
  var className = "foo";
  imageElement.setAttribute("class", className);

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

addImage();
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Javascript regex to remove spaces inside parentheses

Can you provide the specific Javascript regex code for removing spaces only within parentheses? Take for instance: balance( 11010000 ) / balance( 11050000 ) The desired output should be: balance(11010000) / balance(11050000) ...

Node.js Buffer containing data

Creating numerous Buffers sometimes results in non-empty buffers: for (var i = 0; i < 100; i++) { console.log((new Buffer(30)).toString('hex')); } (Partial) Output: 782668013a0000003b00000035000000b0c17900391100003c0000003d00 e4216801ff ...

Using Three.js to create a blurred SVG texture from a canvas

I am attempting to apply an SVG as a texture over a model with UV mapping, but it appears very blurry. I'm using the texture from a 2D canvas, which looks fine on its own, but once applied to the model, it doesn't look good at all. Any suggestion ...

Issues encountered while optimizing JSON file in a ReactJS program

I'm struggling with utilizing Array.prototype.map() in Javascript Specifically, I'm reformatting a JSON file within my react app, which looks like: { "id": 1, "title": "Manage data in Docker", "description": "How to use v ...

Retrieve information from Google Sheets to use in SVG map

While working on a local HTML page, I encountered an issue with my script. I am using the svgMap library to create a map of movies I have seen, pulling data from a Google Sheets document using the opensheet library. The JSON output looks like this: [{"Coun ...

Implementing a dynamic dropdown list with pre-selected values within a while loop

Is there a way to have the selected value in a dropdown list reflect a value given by a JavaScript function that updates a GET parameter in the URL when an option is chosen? <?php while ($row = mysql_fetch_array($res)) { echo '<option value=&ap ...

Trigger an email notification in Google Sheets whenever a designated cell is populated

I am currently exploring ways to enhance collaboration in project management, especially when dealing with numerous stakeholders (Although there are free tools available, integrating new procedures into a public organization's projects can be quite ch ...

jQuery's .html() function does not accept the encoded entity "&amp;"

Whenever I attempt to include a string containing "& (amp)" within the .html() function, it results in an unrecognized expression error. Can you advise me on how to convert the &amp; string or suggest the best method for inserting the desired strin ...

The additional pieces of information transmitted in the state are not being accurately interpreted

I have constants set up that I want to store in the state: const day = "25/02/2020"; const timeStart = "08:00"; const timeEnd = "00:00"; In my Vuex file, I have the following setup: export default new Vuex.Store ({ s ...

Unable to exchange values on the front-end of the next.js app despite the successful operation of the swap function on the back-end

I've built a currency conversion app using next.js and it's running smoothly. However, I'm trying to implement a feature that allows users to easily swap between the From and To currencies. Here is the function code for swapping currencies: ...

How can one ensure that Discord waits for a script to complete running, and how can you prevent Discord from responding until all necessary data has been obtained?

I recently started working with node.js and asynchronous programming, and I'm facing a challenge that has me puzzled. My goal is to create a Discord bot that fetches data from a third-party website. While I can successfully retrieve the data and see i ...

What is the best way to retrieve the client socket id from the HTTP request?

Recently I came across a fascinating challenge. I needed to establish communication between a web browser client and my ExpressJS server using web sockets to quickly display updates made on another client. Additionally, I relied on a standard HTTP connect ...

Learn the process of transferring data from a page to a layout in NUXT

I am in the process of creating a basic website. The goal is to dynamically change the Navbar elements based on the data set in the navLayout within the page template. My plan is to pass this data to the layout and then utilize props to transmit it to the ...

What is the process of exporting a module that has been imported in ES6?

Here are 3 code snippets: // ./src/index.ts const myApp = { test: 1, ... } export default myApp // ./src/app.ts import myApp from './src/index' export default myApp // ./index.vue import { example } from './src/app.ts' console.l ...

Utilizing a variable name to specify an array or object for searching in Javascript and jQuery

Looking to improve my JavaScript skills as a beginner. I have a program that can randomly select an item from an object, but now I want it to pick another item from an object with the same name as the first selection. However, I'm struggling with usin ...

CreatePortalLink directs users to a payment URL instead of a dashboard

I am currently working on a project that utilizes the Stripe payments extension in conjunction with Firebase. The application is built using Next JS. After a user subscribes, I want to provide them with a tab where they can manage their subscription. The ...

Navigating through various arrays within objects on a JSON API with JavaScript: A walkthrough

I am currently working on fetching and displaying data from an API. The specific data I am interested in is located within the 'equipments' array. You can see an example of this array in the image linked below: https://i.sstatic.net/QeBhc.jpg M ...

Verifying the presence of a cookie when the page loads

My goal is to have the browser initially check for a cookie named "yes." If this cookie exists, I would like to show a message. If not, I want to display the following: <input type="button" id='approve' value="approve" onclick="a()"/> &l ...

How can I choose all the items within an Array that fall within a specific DateTime range?

In order to explore the various methods of querying an array table similar to how MySQL works, I have devised this example. Among the 8 queries presented below, the one that is challenging me is Query (6), which involves using Array.find() in a MySQL Date ...

Switching the input of data from a string format to a date format

One of the components in my registration form requires the user to input their start date. I am currently utilizing a MEAN Framework, specifically AngularJs for the front end development. Progress so far: Initially, I attempted using the code snippet bel ...