Question

$('#imgSW').click(function (e) {
var w=window.innerWidth/2;
if (e.pageX > w)(changeUp())
else(changeDown());
});

This worked fine when #imgSw was horizontally centered.
But now, it is placed inside a right div, with liquid width.
How can I get the cursor coordinates just referring the #imgSW, not the window.

Était-ce utile?

La solution

Change your var w for that :

var $this = $(this)
var w=$this.offset().left+($this.width()/2);

And it should work.

Autres conseils

You'll need to get the elements distance from the left edge of the window, and that would be the elements offset from the left, but as that is relevant to the document, you'll have subtract any distance scrolled as well to make it relevant to the visible window.

Then just subtract that distance (and use the proper curlybraces in the if / else) :

$('#imgSW').on('click', function(e) {
    var cursor_x  = e.pageX,
        elem_left = $(this).offset().left,
        wind_left = $(window).scrollLeft();

    var true_left = cursor_x - (elem_left - wind_left);

    var w = window.innerWidth/2;

    if (true_left > w) {
       changeUp();
    } else {
       changeDown();
    }
});
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top