views:

102

answers:

3

I've made a page that uses jQuery to allow you to place <div>s on the page based on your mouse coordinates when you click.

The page

And here's the javascript:

$('document').ready(function() {
    $("#canvas").click(function(e){
    var x = e.pageX - this.offsetLeft;
    var y = e.pageY - this.offsetTop;
    $(document.createElement('div')).css({'left':x + 'px', 'top':y + 'px'}).addClass('tile').appendTo('#canvas');
    });
});

I've found that if you mousedown in the div#canvas and mouseup with your pointer over a placed <div> (or vice versa) then a new <div> doesn't get placed. Why is this?

EDIT:

Ok, so the problem is that the mouse-up and mouse-down events are registering in different elements so it doesn't make a click event. So how do I get my mouse-up part of the click ignore the div.tile elements (the pink rectangles) and register in the div#canvas element to create the click event?

+1  A: 

You need to handle mouseup instead of click.

EDIT: To ensure that the corresponding mousedown happened inside #canvas, yuo can handle it and check, like this:

var mousedownInCanvas = false;

$(document).mouseup(function() { mousedownInCanvas = false });

$('#canvas').mousedown(function() {
    mousedownInCanvas = true;
}).mouseup(function(e) {
    if (!mousedownInCanvas) return;

    var x = e.pageX - this.offsetLeft;
    var y = e.pageY - this.offsetTop;
    $('<div class="tile"></div>').css({ left: x, top: y }).appendTo('#canvas');
});
SLaks
But what if I only want a `div.tile` to be placed if the user moused down within `div#canvas`?
Acorn
You can handle mousedown and check.
SLaks
I'm not having any luck with the method you posted. Any idea why no `<div>` s are getting placed? http://acorn.host22.com/tiles2.html
Acorn
@Acorn: We misspelled the classname. (`title` vs `tile`) If you paste `javascript:void($('.title').addClass('tile'))` into the address bar, a tile will appear in every place that you clicked.
SLaks
@SLaks, works perfectly! Thank you for the help!
Acorn
A: 

A click consists of a mouse-down and a mouse-up event. Since your mouse-down originated in another div, the secondary div will not register a click.

BradBrening
Is there any way I can make my mouse-up event register in the `div#canvas` even if there is a `div.tile` in the way?
Acorn
+1  A: 

I believe its not a click unless the mouseup and mouse down occur on the same element.

From the jQuery docs:

The click event is sent to an element when the mouse pointer is over the element, and the mouse button is pressed and released. Any HTML element can receive this event.

More info here

DannyLane