views:

11

answers:

1

Hi,

I wonder if someone can help me. I know JS quite well but am completely new to JQuery...

I've got an image which is being loaded dynamically vis a call to UpdateImage()

    $.fn.image = function (src, f) {
        return this.each(function () {
            var i = new Image();
            i.src = src;
            i.onload = f;
            this.appendChild(i);
        });
    }

    function UpdateImage() {
        $("#Screen").image("./AJAX/UI/GetImage.aspx", function () {
            //alert('ok');
        });
    }

After the image has loaded, I want the user to be able to click anywhere on it and use the X/Y coordinates of the click in an AJAX call.

I know how to do this in pure JS but I get the feeling there must be a more elegant JQuery method...

Currently, I'm trying this:

    $(document).ready(function () {
        $("#Screen").click(function () {
            alert(this.x + ', ' + this.y);
        });
        UpdateImage();
    });

Unfortunately, the X and Y retrieved are constant irrespective of click location. (x: 9, y: 1019).

Question: As the image is almost top-left on the page, I'm surprised at the Y value - what does it represent? I assumed that if it wasn't mouse co-ords, it would be element location - but this doesn't seem right - is Y here positive in the "Up" direction rather than down (as I expected)?

I've Googled and found lots of solutions which I consider to be overkill - They apply to any element type and rely on calculating element position then mouse cursor position and doing some maths - This seems very inelegant and error-prone as it's browser-dependent.

Question: Is the approach I'm taking correct? Should I be using a JQuery UI widget to display the image? For the sake of argument, assume the image is a ScreenShot and is likely to be larger than the browser window - I'm currently relying on the browser for scrolling, etc. but again suspect there may be a better way?

In short, any advice from some JQuery experts would be much appreciated - especially if you could point me at a good JQuery resource (I've found the manual but that is more useful for method signatures than working out which approach is correct when using JQuery)

In case it affects your responses, the element I'm using to store the image is shown below

<div id="Image"><img id="Screen"/></div>

Many thanks in advance for any help you can provide.

+1  A: 

Did you try using the coords attached to the click event and not the element:

$(document).ready(function () {
        $("#Screen").click(function (e) {
            alert(e.pageX + ', ' + e.pageY);
        });
        UpdateImage();
    });
prodigitalson
Aww, beat be to it :P
Mark
Damn. I tried to access e and got nothing - I missed the e param out of the method declaration. Thanks for spotting a schoolboy error :)
Basiclife
Sometimes it just takes a second pair of eyes :-)
prodigitalson