Joel
Joel

Reputation: 2721

very simple javascript image load question

Very new to javascript here folks, so forgive the newbie question.

I want to load a very simple and small image with javascript. Can I do an that is triggered by an onload?

Note: The reason for this is I have a section of a website that requires javascript to work properly. I want to have a little green circle to show a user that they have javascript installed.

Upvotes: 0

Views: 472

Answers (3)

Juraj Blahunka
Juraj Blahunka

Reputation: 18513

The most simple and easiest way to do this is using a javascript library, which utilizes load or ready functions. Example with jquery, launches, when document is ready :)

$(function () {
    $('body').append('<img src="/img/js-is-working.jpg" />');
});

Upvotes: 0

Christopher Tokar
Christopher Tokar

Reputation: 11887

Pretty simple (no need to import a library):

<!-- somewhere in your document's <body> tag -->
<div id="divId">

</div>

<!-- in your document's <head> tag, or a separate .js file -->
<script>
// addLoadEvent function for executing JavaScript on page load
// adds the event in such a way that any previously added onload functions 
// will be executed first.
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

addLoadEvent(function() {
  document.getElementById('divId').innerHTML = "<img src='yourimage.gif' />"
  // add more code here if necessary
});



</script>

Upvotes: 3

jpabluz
jpabluz

Reputation: 1312

This code assumes that you don't use JQuery.

var preloadedImage;    

function PageIsLoaded(e)
{
    preloadedImage = new Image();
    img.src = 'pathToYourImage.jpg';
    // preloading
    img.onLoad = function () { displayImage() };
}

function displayImage()
{  
    // Assuming that this id refers to an IMG tag
    var imgHolder = document.getElementById('imgHolder');
    imgHolder = preloadedImage;
}

Upvotes: 0

Related Questions