JavaScript Working With Images

Raja Tamil
The Startup
Published in
8 min readDec 7, 2020

--

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…

--

--

Raja Tamil
The Startup

👇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