The Startup

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

Follow publication

Member-only story

JavaScript Working With Images

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.

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

The Startup
The Startup

Published in The Startup

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

Raja Tamil
Raja Tamil

Written by Raja Tamil

👇click the link and get 80% OFF on the premium web development courses (HTML5, CSS3, JavaScript ES6, Vue JS 3 & Firebase 10 https://softauthor.com

Responses (1)

Write a response