HomeLanguagesJavascriptHow to pass image as a parameter in JavaScript function ?

How to pass image as a parameter in JavaScript function ?

We all are familiar with functions and their parameters and we often use strings, integers, objects, and arrays as a parameter in JavaScript functions but now will see how to pass an image as a parameter in the JavaScript functions. We will use vanilla JavaScript here.

Approach: First, create a function that receives a parameter and then calls that function. The parameter should be a string that refers to the location of the image.

Syntax:

function displayImage (picUrl) {
    ...
}

displayImage('/assets/myPicture.jpg')

Example: In this example, we will display an image inside a DIV whose id is “imgDiv”.

<div id="imgDiv">
    <!-- Here we show the picture -->
</div>

Steps:

  1. First, create a markup that has an h1 and a div tag whose id is imgDiv in which we are going to insert the image.
  2. Create a script tag in which we all are going to make all our logics.
  3. Create a variable named divLocation and assign the DOM element of that div into the variable.
  4. Now create an img element with document.createElement() and assign it into variable imgElement.
  5. Then assign the URL of the image to its href attribute by using imgElement.href = /image location/.
  6. Now append the img Element to the div element by append() method.

html




<!DOCTYPE html>
<html>
<body>
    <center>
        <h1>Hello GFG</h1>
        <div id="imgDiv"></div>
    </center>
  
    <script>
        var Pic = ""
          
        function displayImage(pic) {
            let divLocation = document.getElementById("imgDiv");
            let imgElement = document.createElement("img");
            imgElement.src = pic
            divLocation.append(imgElement);
        }
          
        Pic =
          
        displayImage(Pic);
    </script>
</body>
</html>


Output:

 

RELATED ARTICLES

Most Popular

Dominic
32548 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6922 POSTS0 COMMENTS
Nicole Veronica
12038 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12144 POSTS0 COMMENTS
Shaida Kate Naidoo
7058 POSTS0 COMMENTS
Ted Musemwa
7299 POSTS0 COMMENTS
Thapelo Manthata
7016 POSTS0 COMMENTS
Umr Jansen
7005 POSTS0 COMMENTS