34,781 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
Can we change image src using JavaScript?You can change an HTML image src attribute programatically by using JavaScript. First, you need to grab the HTML element by using JavaScript element selector methods like getElementById() or querySelector() and assign the element to a variable.
How do I change an image using JavaScript?Change the Source of an Image Using the src Property in JavaScript. To change the source or src of an image, you need to add an id or class to the image tag. You can get the image element using the name of the id or class , and you can change the source or src of the image using the src property.
Can you change img src?The required src attribute specifies the URL of an image. Note: The src property can be changed at any time. However, the new image inherits the height and width attributes of the original image, if not new height and width properties are specified.
How do I change the source of an image in click?Answer: Use the jQuery attr() Method
You can use the attr() method to change the image source (i.e. the src attribute of the <img> tag) in jQuery. The following example will change the image src when you clicks on the image.
|