0

I'm new to Javascript and I'm triyng to perform an onClick event on an image in a external .js file using the html tag

<script type="text/javascript" src="embed.js">

The code inside "embed.js" is the following

var image1=new Image();
image1.src="img.gif"
document.write('<IMG src='+image1.src+'>');


$(document).ready( function()
{
 $(image1).click( function()
{
    alert("Hello World");
    });
});   

As you can see, I'd like to show an alert when somebody click on the image, but the code I've posted doesn't work. Could you help me? Thanks! :)

@JD it the html code is

<html>
<head>
    <title></title>

</head>

<body>
<script src="embed.js"></script>
</body>


</html>
4
  • = new Image() is your problem here.. it should be a selector.. $('#image1') maybe? post your html./ Commented Apr 8, 2014 at 16:47
  • 2
    PS. Don't use document.write(). Commented Apr 8, 2014 at 16:48
  • 1
    @JFit: OP wants to create an image and add a listener, not add a listener to an existing image. Commented Apr 8, 2014 at 16:49
  • document.write is bad practice. Reasons. Commented Apr 8, 2014 at 16:50

3 Answers 3

2

The image that you attach the onclick to and the image that you put on the page are not the same.

Explanation: The string that you pass to document.write is parsed by the browser to create a new image element (albeit one that has the same src) while image1 is a different image instance that is only in memory (not on the page), but it has the event listener.

To fix, replace

document.write('<IMG src='+image1.src+'>');

with

document.body.appendChild(image1);

Now you're dealing with only one image, which gets put on the page and the event listener.

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

Comments

0

All the answers are correct

but you can insert the "image1" object directly in the DOM.

Something like this:

$(document).ready( function(){
    // Take care with the scope of image1

    var image1 = $("<img/>").attr("src","img.gif").appendTo("parentElementInDOMselector");

    image1.click( function(){
        alert("Hello World");
    });

});  

You can use appendTo, preppendTo, or functions like html(); replace(); etc...

Comments

-1

Your selections are off, try:

$("document").ready( function()
{
 $("#image1").click( function()
{
    alert("Hello World");
    });
});   

and add an id to the image tag

<img id='image1' ...

JS fiddle http://jsfiddle.net/YS95J/

1 Comment

The OP wants to create an image and add a listener, not add a listener to an existing image.

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.