0

I'm trying to create an image on the page using JavaScript, however even the alert('This function works!') does not work! I have no idea why it doesn't work, Help please!

<!DOCTYPE html>
<html>
    <head>
        <script language="javascript">
        function loadImages() {    
            myImage = new Image();
            myImage.src = "./images/A_01.png";
            document.createElement(myImage);
            document.alert('This function works!');
        }
        </script>
    </head>
    <body>
        <p style="text-align: center">
            <button>
                <img src="images/K_01.png" onclick="loadImages()" alt="button" style="vertical-align: bottom">
                 onvert
            </button>
        </p>
    </body>
</html>
2
  • 2
    language="javascript" - that attribute is deprecated. Just omit it! Commented Apr 27, 2014 at 13:49
  • @ThiefMaster that's the least of his problems. Commented Apr 27, 2014 at 13:51

2 Answers 2

2

You never append the image to the DOM. Use appendChild() for that:

function loadImages(){ 

  myImage = new Image();
  myImage.src = "./images/A_01.png";

  document.body.appendChild( myImage );

}

createElement() actually will create a new element. You can use this as an alternative to your new Image() constructor. It, however, does not add the created element to the DOM. Hence it will remain invisible until you do add it to the DOM.

Sign up to request clarification or add additional context in comments.

Comments

0

Don't put an image in the button element. Add CSS to it to apply the image as a background:

 <button style="background-image:url(path/to/image.png" id="btn" alt="button">

I've updated your javascript to attach a listener unobstrusively, ensured the element is appended to the body, and called alert properly:

var btn = document.getElementById('btn');
btn.addEventListener('click', loadImages);

function loadImages(){ 
  myImage = new Image();
  myImage.src = "./images/A_01.png";
  document.body.appendChild(myImage);
  alert('This function works!');
}

http://jsfiddle.net/8Q5UA/

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.