How to display image in javascript

32,080

How to display image in javascript

In this JavaScript tutorial, you’re going to learn 14 common scenarios you’ll probably run into if you haven’t already when working with images.

1. Show Image in Plain HTML

Create a static image tag with a src attribute with an image URL in the HTML file.

<img src="https://picsum.photos/200/300" />

output:

As you can see, I use the picsum website for demonstration purposes. It lets me get a random image URL with specific dimensions passed at the end of the URL.

Pretty straight forward right?

Let’s see how to set a src attribute dynamically via JavaScript next.

2. Set Src Attribute in JavaScript

In the HTML file, create an HTML image tag like so:

<img/> 

In JavaScript, get a reference to the image tag using the querySelector() method.

const img = document.querySelector("img"); 
img.src = "https://picsum.photos/200/301";

Recommended → JS Variables

Then, assign an image URL to the src attribute of the image element.

Alternatively, you can set a src attribute to the image tag using the square brackets syntax like this:

img["src"] = "https://picsum.photos/200/301";

output:

3. Set Multiple Src Attributes in JavaScript

Let’s say you have three image elements in the HTML page in different parts.

<img/> // image 1
...
<img/> // image 2
...
<img/> // image 2

Using ID or class attribute, you can easily target each image element separately to set a different value to the src attribute which I will cover later in this chapter.

Let me show you what 🛑 NOT to do when having multiple static image tags on your HTML page.

const img = document.querySelector("img"); 

In the previous example, I used the querySelector() method to target the image element which works fine for a single image element.

To get a reference to all three image elements, we’ll need to use querySelectorAll().

const img = document.querySelectorAll("img"); 

This will get all of the image element references and create a Node List Array from them.

img[0].src = "https://picsum.photos/200/301"; // image 1
img[1].src = "https://picsum.photos/200/302"; // image 2
img[2].src = "https://picsum.photos/200/303"; // image 3

This works fine, but there is one problem with this approach.

Let’s say you no longer need the first image element and remove it from the HTML code.

Guess what?

The second and third image elements will end up having the first and second images.

4. Create Image Element in JavaScript

Create an image element using the createElement() method on the document object.

Then, set an image URL to its src attribute.

const img = document.createElement("img");
img.src = "https://picsum.photos/200/301";
document.body.appendChild(img);

Finally, add the image element to the DOM hierarchy by appending it to the body element.

Alternatively, you can use the Image() constructor which creates a new HTMLImageElement instance and its functionality is equivalent to document.createElement(“img”).

Optionally, you can pass width and height parameters to it.

const img = new Image(100, 200); // width, height
img.src = "https://picsum.photos/200/301";
document.body.appendChild(img);

It will be equivalent to this in HTML:

<img width="100" height="200" src="https://picsum.photos/200/301">

5. Add Inline Style to the Image in JavaScript

Using the style property, we can apply style to the image element directly in JavaScript.

As you can see in the example below, I’ve applied a border as well as borderRadius styles to it.

let img = document.createElement("img");
img.src = "https://picsum.photos/200/301";

img.style.border = "10px solid orange";
img.style.borderRadius = "10px";

document.body.appendChild(img);

How to display image in javascript

6. Add ID Attribute to the Image in JavaScript

Adding multiple styles to the image element individually would be tedious.

Instead, let’s create a new CSS rule inside the style tags or an external CSS file with an ID selector like below.

#img-rounded-border {
  border:10px solid red;
  border-radius:10px;
}

Then, assign it to the ID attribute of the image element using its ID property.

img.id = "img-rounded-border";

As you know, it’s pretty straight forward as the value of the ID attribute should not be duplicated in a single page.

Alternatively, you can invoke the setAttribute() method on the img object with two arguments: the attribute name and the value.

img.setAttribute("id", "img-rounded-border");

7. Add Class Attribute to the Image in JavaScript

Unlike the ID attribute, you can add multiple class names in a single image element or the same class name in multiple image elements or combinations of both.

Let’s say we have a CSS rule with a class name called .img-rounded-border.

.img-rounded-border {
  border:10px solid red;
  border-radius:10px;
}

Then, we can add this class to the image element using the add() method on the classList property passing the class name as an argument.

img.classList.add("img-rounded-border");

If you want to add another class to the same image element, you’ll have to use the add() method again.

img.classList.add("img-rounded-border");
img.classList.add("my-second-class");

Alternatively, you can use the setAttribute() method to add a single or multiple class attributes to the image element in a single line.

img.setAttribute("class", "img-rounded-border");
img.setAttribute("class", "img-rounded-border my-second-class");

When you use setAttribute, all of the previous classes added to the element will be reset.

8. Attach a Click Event to the Image Element

To attach a click event to the image element, invoke the addEventListener() method on the img object.

This will take two arguments:

  1. click = event name and
  2. function() {} = callback function.
let img = document.createElement("img");
img.src = "https://picsum.photos/200/301";

img.addEventListener("click", function() {
  console.log("clicked");
})

document.body.appendChild(img);

9. Toggle CSS Selector When an Image is Clicked

Let’s say you want to add and remove the border of the image when a user clicks it using the class .img-rounded-border.

.img-rounded-border {
  border:10px solid red;
  border-radius:10px;
}

All you have to do is call the toggle() method passing the class name as an argument on the classList property inside the click event callback function.

img.addEventListener("click", function() {
  img.classList.toggle("img-rounded-border");
})

Alternatively, the event object which is passed into the callback function can be used to access the image element to add or remove the class.

img.addEventListener("click", function(e) {
    e.target.classList.toggle("img-rounded-border");
})

How to display image in javascript

10. Get a Selected Image Item When Clicked

We can get any piece of information about the selected item using the event object which is passed into the callback function as I mentioned earlier.

Let’s say you want to get the selected image url.

Using e.target.src, you can easily get the image URL which is a value of the src attribute.

let img = document.createElement("img");
img.src = "https://picsum.photos/200/301";

img.addEventListener("click", function(e) {
  console.log(e.target.src);
})

document.body.appendChild(img);

11. Create Multiple Images in JavaScript

Let’s say we want to create 10 images dynamically.

First, iterate 10 times using the for loop.

for(let i = 0; i < 10; i++) {
  console.log(i); // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
}

Then, create an image element inside the loop and set the src attribute with a random image url from picsum.

for(let i = 0; i < 10; i++) {
   const img = document.createElement("img");
   img.src = "https://picsum.photos/200/301";
}

Append all 10 images to the body element.

for(let i = 0; i < 10; i++) {
   const img = document.createElement("img");
   img.src = "https://picsum.photos/200/301";
   document.body.appendChild(img);
}
How to display image in javascript

Let’s give some margins between the images.

Create a new CSS rule inside the style tags or an external CSS file.

.img-margin {
  margin:10px;
}

Then, add it to the image elements inside the loop using the add() method.

for(let i = 0; i < 10; i++) {
  const img = document.createElement("img");
  img.src = "https://picsum.photos/200/301?id=" + i;
  img.classList.add("img-margin");
  document.body.appendChild(img);
}

12. Conditional Style in the Loop Image

Let’s change a specific image with a different style.

Let’s change the borderRadius property for the 6th item using an if condition.

for(let i = 0; i < 10; i++) {
  const img = document.createElement("img");
  img.src = "https://picsum.photos/200/301?id=" + i;
  if(i === 5) {
    img.style.borderRadius = "50%";
  }
  img.classList.add("img-margin");
  document.body.appendChild(img);
}
How to display image in javascript

13. Add Click Events to All the Images

Attach an addEventListener() method to the img element on each iteration which takes two arguments.

  1. click = event name and
  2. function() {} = callback function.

Make sure to use let instead of var in the for loop header when declaring the i variable to avoid hoisting which is one of the common issues that you’ll run into when dealing with a clicking event inside a loop like this.

To learn more about hoisting, have a look at my other blog:
Adding Click Event Listeners In A Loop In JavaScript

for(let i = 0; i < 10; i++) {
  const img = document.createElement("img");
  img.src = "https://picsum.photos/200/301?id=" + i;
  img.addEventListener("click", function() {
   console.log(i); // selected index number
  })
  document.body.appendChild(img);
}

14. Apply CSS Class To Only The Clicked Image

As I’ve added the img-margin class to each img element, it will give some space between the images in the initial load.

for(let i = 0; i < 10; i++) {
  const img = document.createElement("img");
  img.src = "https://picsum.photos/200/301?id=" + i;
  img.classList.add("img-margin");
  img.addEventListener("click", function() {
   img.classList.add("img-rounded-border");
  })
  document.body.appendChild(img);
}

When any img element is clicked, the img-rounded-border class gets added to that element which will show a red thick border around it.

How to display image in javascript

Nice!

But what if we want to add the img-rounded-border class only to the selected image element and not to all of the others.

One of the solutions to fix this is to remove the .img-rounded-border class from all the images first before adding it to the clicked image.

for(let i = 0; i < 10; i++) {
  const img = document.createElement("img");
  img.src = "https://picsum.photos/200/301?id=" + i;

  img.setAttribute("class", "img-margin");

  img.addEventListener("click", function() {

    for (var i = 0; i < images.length; i++) {
      images[i].classList.remove('img-rounded-border');
    }
    img.classList.add("img-rounded-border");
  })
  document.body.appendChild(img);
}
How to display image in javascript

It is always fun working with images in JavaScript. I hope you enjoyed this tutorial of 14 common scenarios working with images.

I know there are many more scenarios than this. Please let me know if you would like me to add anything to this tutorial!

Recommended

  • JavaScript Image Carousel
  • JavaScript For Loop Click Event Issues & Solutions
  • JavaScript Accordion Menu
  • JavaScript Dynamic Radio Buttons
  • JavaScript Dynamic Select Drop Down List
  • JavaScript Find() Explained
  • JavaScript Filter() vs Find() Explained

How do you insert an image into JavaScript?

You can access an <input> element with type="image" by using getElementById(): var x = document. getElementById("myImage"); Tip: You can also access <input type="image"> by searching through the elements collection of a form.

How do I display a JPEG image in HTML?

Chapter Summary.
Use the HTML <img> element to define an image..
Use the HTML src attribute to define the URL of the image..
Use the HTML alt attribute to define an alternate text for an image, if it cannot be displayed..

How do I display an image in API?

Display an Image from an API Response.
Open the request in the API tab on the right of the editor..
Select the Events section. You should see an Event for each status code that the API returns..
Open the Event for the status code your image URL is associated with (typically it will be 200: OK)..
Click the plus..

How do you make an image appear in HTML?

To insert image in an HTML page, use the <img> tags. It is an empty tag, containing only attributes since the closing tag is not required. Just keep in mind that you should use the <img> tag inside <body>… </body> tag.