Christos Hayward
Christos Hayward

Reputation: 5993

Why is my image not loading?

At http://blajeny.com I have:

jQuery('body').click(function(event_object)
    {
    spark(event_object.pageX, event_object.pageY);
    });

function spark(x, y)
    {
    console.log('Spark called.');
    var image_object = new Image();
    image_object.onLoad = function()
        {
        image_object.style.position = 'absolute';
        image_object.style.zIndex = 1;
        image_object.style.top = y;
        image_object.style.left = x;
        }
    image_object.src = '/img/spark.png';
    }

The intended effect, at this stage, is to load an image at the X and Y where the user clicked. (I want to do other things as well, like animate it, but right now I'm trying to get the image to show up where the user clicked.)

The javaScript console shows that the handler is being called, however I am not seeing what I expect, a hazy blue circle immediately below and to the right of the point where the mouse was clicked.

What can/should I do differently so it loads a fresh image below and to the right of the clicked coordinates?

Thanks,

Upvotes: 0

Views: 78

Answers (4)

Denys Séguret
Denys Séguret

Reputation: 382474

You never append the image to the DOM, that's why you can't see it.

You can do

document.body.appendChild(image_object);

You must also replace onLoad by onload and specify the top and left position with an unit :

image_object.onload = function()  {
    image_object.style.position = 'absolute';
    image_object.style.zIndex = 1;
    image_object.style.top = '100px';
    image_object.style.left = '100px';
}

Demonstration

Upvotes: 0

Saad Ulde
Saad Ulde

Reputation: 89

I agree, first create an element with the "img" tag, assign the src value to it, and append it to the current div (in this case its the body), like so

var imgTag = document.createElement("img");
imgTag.src = '/img/spark.png';
document.body.appendChild(imgTag);

Hope this helps.

Upvotes: 0

srosh
srosh

Reputation: 124

I don't see you appending the image to DOM that's probably why you're not seeing it

$('body').append($(image_object));

Upvotes: 0

Salman
Salman

Reputation: 9447

As far as I know, the onLoad should be onload

var image_object = document.createElement('img');
image_object.onload = function() { // Note the small onload
    // your code
}

// Also, append the image_object to DOM
document.body.appendChild(image_object);

Upvotes: 2

Related Questions