How to create a hidden <img> in JavaScript?

110,548

Solution 1

I'm not sure I understand your question. But there are two approaches to making the image invisible...

Pure HTML

<img src="a.gif" style="display: none;" />

Or...

HTML + Javascript

<script type="text/javascript">
document.getElementById("myImage").style.display = "none";
</script>

<img id="myImage" src="a.gif" />

Solution 2

This question is vague, but if you want to make the image with Javascript. It is simple.

function loadImages(src) {
  if (document.images) {
    img1 = new Image();
    img1.src = src;
}
loadImages("image.jpg");

The image will be requested but until you show it it will never be displayed. great for pre loading images you expect to be requests but delaying it until the document is loaded.

Example

Solution 3

How about

<img style="display: none;" src="a.gif">

That will disable the display completely, and not leave a placeholder

Solution 4

You can hide an image using javascript like this:

document.images['imageName'].style.visibility = hidden;

If that isn't what you are after, you need to explain yourself more clearly.

Solution 5

Try setting the style to display=none:

<img src="a.gif" style="display:none">
Share:
110,548

Related videos on Youtube

Prasad
Author by

Prasad

I am back

Updated on July 09, 2022

Comments

  • Prasad
    Prasad almost 2 years

    How can you make a simple tag like <img src="a.gif"> hidden programmatically using JavaScript?

    • Billy
      Billy almost 15 years
      Can you clearly state what you wanna do?
    • Prasad
      Prasad almost 15 years
      <img src="a.gif" style="display:none">
  • Nabin
    Nabin over 7 years
    display: none; is what I needed. Thank you
  • noogui
    noogui almost 7 years
    what if i want to show the image? should it be .style.display = true; ?
  • Steve Wortham
    Steve Wortham over 6 years
    To show the image it'd be .style.display = "inline-block" which would be the default display behavior of an img. All possible display options are described here... css-tricks.com/almanac/properties/d/display