Test Javascript

Javascript set img src

I am probably missing something simple but it’s quite annoying when everything you read doesn’t work. I have images which may be duplicated many times over the course of a dynamically generated page. So the obvious thing to do is to preload it and use that one variable as the source all the time.

var searchPic; function LoadImages() < searchPic = new Image(100,100); searchPic.src = "XXXX/YYYY/search.png"; // This is correct and the path is correct >
 document["pic1"].src = searchPic; 

However, the image is never set properly in FireBug when I query the image I get [object HTMLImageElement] as the src of the image In IE I get:

http://localhost:8080/work/Sandbox/jpmetrix/[object] 

10 Answers 10

You should be setting the src using this:

document["pic1"].src = searchPic.src; 

Pure JavaScript to Create img tag and add attributes manually ,

var image = document.createElement("img"); var imageParent = document.getElementById("body"); image.id = "id"; image.className = "class"; image.src = searchPic.src; // image.src = "IMAGE URL/PATH" imageParent.appendChild(image); 

Set src in pic1

document["#pic1"].src = searchPic.src; 
document.getElementById("pic1").src= searchPic.src; 

j-Query to archive this,

Also, one way to solve this is to use document.createElement and create your html img and set its attributes like this.

var image = document.createElement("img"); var imageParent = document.getElementById("Id of HTML element to append the img"); image.id = "Id"; image.className = "class"; image.src = searchPic.src; imageParent.appendChild(image); 

REMARK: One point is that Javascript community right now encourages developers to use document selectors such as querySelector , getElementById and getElementsByClassName rather than document[«pic1»].

Читайте также:  Таблица значений цвета html

Источник

How do I load a local image using JS?

Problem here though is that the images should not be visible on the page but are when loaded using markup. I simply want to load them through the script without first having to add them in the markup. I realize this is an extremely trivial problem, but searching for a solution has given me nothing. I tried this approach:

But this did not work. Can someone with some common JS sense please give me some input on this issue. EDIT : So this is how the markup/JS looks now, the images are still displayed and the final merge of the images won’t show. The error I get is:

IndexSizeError: Index or size is negative or greater than the allowed amount [Stanna vid fel] var image1 = context.getImageData(0, 0, width, height); 
     

Blended image

Источник

How to add an image in a HTML page using javascript ?

Examples of how to add an image in a HTML page using javascript:

Add an image using javascript

Let’s create a variable image with createElement («img»):

var img = document.createElement("img"); 

then indicate the name of the image (Note: if the image is not in the same directory as the html document, we can also specify the full path to the image for example ‘./path_to_img/matplotlib-grid- 02.png ‘):

img.src = "matplotlib-grid-02.png"; 

and finally display the image in the html page

var block = document.getElementById("x"); block.appendChild(img); 
         var img = document.createElement("img"); img.src = "matplotlib-grid-02.png"; var div = document.getElementById("x"); div.appendChild(img); //block.setAttribute("style", "text-align:center");    

How to add an image in a HTML page using javascript ?

Change the style of the div element

You can then for example modify the style of the div containing the image with

         var img = document.createElement("img"); img.src = "matplotlib-grid-02.png"; var div = document.getElementById("x"); div.appendChild(img); div.setAttribute("style", "text-align:center");    

How to add an image in a HTML page using javascript ?

Update the style of the image

You can also change the style of the image with

         var img = document.createElement("img"); img.src = "matplotlib-grid-02.png"; img.setAttribute("style", "margin-top: 80px;"); var div = document.getElementById("x"); div.appendChild(img); div.setAttribute("style", "text-align:center");    

How to add an image in a HTML page using javascript ?

References

Benjamin

Greetings, I am Ben! I completed my PhD in Atmospheric Science from the University of Lille, France. Subsequently, for 12 years I was employed at NASA as a Research Scientist focusing on Earth remote sensing. Presently, I work with NOAA concentrating on satellite-based Active Fire detection. Python, Machine Learning and Open Science are special areas of interest to me.

Skills

Источник

How to Display Image With JavaScript

JavaScript is a dynamic scripting language used for dynamic effects on websites. Moreover, the web pages contain images using the HTML tag. Sometimes the page takes a long time to load, so developers prefer to add images using JavaScript image tags that load dynamically and take less time to load or display on any click.

This article will describe the process for displaying images using JavaScript.

How to Display an Image With JavaScript?

For displaying images with JavaScript, use the “createElement()” method to create an HTML element node. To achieve this, it takes “img” as a parameter.

Syntax
For creating an element node, use the given syntax:

Example 1: Display Image With JavaScript
In this example, there is no need to add an HTML code because we will add an image using JavaScript. For this purpose, write out the following code in the JavaScript file:

function displayImage ( src , width , height ) {
var img = document. createElement ( "img" ) ;
img. src = src ;
img. width = width ;
img. height = height ;
document. body . appendChild ( img ) ;
}

In the above code snippet:

  • Define a function “displayImage()” with image source “src”, “width”, and “height” as a parameter.
  • Add an image tag or element in JavaScript utilizing the “createElement()” method.
  • Set the image properties like source, width, and height of an image.
  • Then, add the image to the HTML body using the “document.body.appendChild()” method.

Now, call the function “displayImage()” and pass the height, width, and source of an image as an argument:

In the next example, check out how to show an image on a button click.

Example 2: Display Image on Button Click With CSS Class
This example is all about how a CSS class can be used to display an image in JavaScript and how the image will appear when the button is clicked. First, we will create a button in an HTML file that calls the “displayImage()” function when the button is clicked:

Let’s create a CSS class “imageFeatures” to set the image attributes such as “length”, and “width” of an image:

Define a function “displayImage()” with a single parameter src. Then, add an image element using the createElement() method, and set the source of an image. Now, add the class “imageFeatures” for setting the image attributes using the “classList.add()” method. Finally, append the image tag in a document using the “document.body.appendChild()” method:

function displayImage ( src ) {
var img = document. createElement ( "img" ) ;
img. src = src ;
img. classList . add ( "imageFeatures" ) ;
document. body . appendChild ( img ) ;
}

As you can see, the image is displayed on the button click without any delay:

We have displayed the image with the help of JavaScript.

Conclusion

To display an image with JavaScript, use the “createElement()” method for creating an image tag. More specifically, the createElement() method is used to create an element node. In this article, we described the process for displaying images using JavaScript.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.

Источник

Javascript write image to page

Last updated: Jan 12, 2023
Reading time · 3 min

banner

# Create an Image Element using JavaScript

To create an image element:

  1. Use the document.createElement() method to create the img element.
  2. Use the setAttribute() method to set the src attribute on the element.
  3. Add the element to the page using the appendChild() method.

Here is the HTML for the examples.

Copied!
DOCTYPE html> html lang="en"> head> title>bobbyhadz.comtitle> meta charset="UTF-8" /> head> body> div id="box">div> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const image = document.createElement('img'); // 👇️ Local image // image.setAttribute('src', 'my-img.png'); // 👇️ Remote image image.setAttribute( 'src', 'http://bobbyhadz.com/images/blog/javascript-show-div-on-select-option/banner.webp', ); image.setAttribute('alt', 'nature'); image.setAttribute('height', 350); // 👈️ height in px image.setAttribute('width', 550); // 👈️ width in px // 👇️ optionally style the image image.style.border = '5px solid yellow'; image.onerror = function handleError() console.log('Image could not be loaded'); // 👇️ Can set image.src to a backup image here // image.src = 'backup-image.png' // 👇️ Or hide image // image.style.display = 'none'; >; image.onload = function handleImageLoaded() console.log('image loaded successfully'); >; const box = document.getElementById('box'); box.appendChild(image);

We used the document.createElement method to create the img element.

Copied!
const image = document.createElement('img');

Источник

Оцените статью