32,080 Show
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 HTMLCreate a static image tag with a src attribute with an image URL in the HTML file.
output:
Pretty straight forward right? Let’s see how to set a src attribute dynamically via JavaScript next. 2. Set Src Attribute in JavaScriptIn the HTML file, create an HTML image tag like so:
In JavaScript, get a reference to the image tag using the querySelector() method.
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:
output: 3. Set Multiple Src Attributes in JavaScriptLet’s say you have three image elements in the HTML page in different parts.
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.
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().
This will get all of the image element references and create a Node List Array from them.
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 JavaScriptCreate an image element using the Then, set an image URL to its src attribute.
Finally, add the image element to the DOM hierarchy by appending it to the body element. Alternatively, you can use the Optionally, you can pass width and height parameters to it.
It will be equivalent to this in HTML:
5. Add Inline Style to the Image in JavaScriptUsing 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.
6. Add ID Attribute to the Image in JavaScriptAdding 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.
Then, assign it to the ID attribute of the image element using its ID property.
Alternatively, you
can invoke the
7. Add Class Attribute to the Image in JavaScriptUnlike 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.
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.
If you want to add another class to the same image element, you’ll have to use the add() method again.
Alternatively, you can use the setAttribute() method to add a single or multiple class attributes to the image element in a single line.
8. Attach a Click Event to the Image ElementTo attach a click event to the image element, invoke the addEventListener() method on the img object. This will take two arguments:
9. Toggle CSS Selector When an Image is ClickedLet’s say you want to add and remove the border of the image when a user clicks it using the class .img-rounded-border.
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.
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.
10. Get a Selected Image Item When ClickedWe 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.
11. Create Multiple Images in JavaScriptLet’s say we want to create 10 images dynamically. First, iterate 10 times using the for loop.
Then, create an image element inside the loop and set the src attribute with a random image url from picsum.
Append all 10 images to the body element.
Let’s give some margins between the images. Create a new CSS rule inside the style tags or an external CSS file.
Then, add it to the image elements inside the loop using the add() method.
12. Conditional Style in the Loop ImageLet’s change a specific image with a different style. Let’s change the borderRadius property for the 6th item using an if condition.
13. Add Click Events to All the ImagesAttach an addEventListener() method to the img element on each iteration which takes two arguments.
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.
14. Apply CSS Class To Only The Clicked ImageAs I’ve added the img-margin class to each img element, it will give some space between the images in the initial load.
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 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.
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
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.
|