JavaScript Working With Images

Raja Tamil
Dec 7, 2020 · 8 min read

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

1. Show Image in Plain HTML

Create a static image tag with an 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 an 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 an 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 on 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 it’s functionally 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 border radius 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);

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 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 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");
})

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);
}

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 border radius 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);
}

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.

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

I’ve added an img-margin class to each img element which 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.

Nice!

But what if we want to add the img-rounded-border class only to the selected image element not 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);
}

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!

The Startup

Get smarter at building your thing. Join The Startup’s +724K followers.

Raja Tamil

Written by

Instructor/Owner of SoftAuthor! http://softauthor.com/

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +724K followers.

Raja Tamil

Written by

Instructor/Owner of SoftAuthor! http://softauthor.com/

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +724K followers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store