0

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.

3 Answers 3

3

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>
Sign up to request clarification or add additional context in comments.

1 Comment

@Anonymous well that would be dependant if you are doing a small project like a homework or a bigger project.
0

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;
}

Comments

0

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" />');
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.