GMchris GMchris - 2 years ago 147
jQuery Question

Event on back elements doesn't trigger in jQuery

Alright, I have a chess board with all the spots and pieces. It's generated

with two four cycles from a 2D array. The idea is, that you should be able to drag a chess piece (something I've already implemented correctly), and let it go in a valid position. The letting go part should trigger an event in the actual board spots. So each of the 64 spots have an even listener that looks like this.

var col,row;
col = $(this).attr("column");
row = $(this).attr("row");
Game.current = undefined;


The function triggers normally when I click on a square in the board, however when I drag and drop a chess piece there, it doesn't register that the mouse is up. It let's go of the piece, however since the cursor is directly over the chess piece and said piece "blocks" the cursor from being directly above the spot. It is also worth noting that my HTML structure is like this.


By which I mean, that the pawns, bishop etc., aren't inside the spots, so the event doesn't have anything to "bubble" through.

Answer Source

A better approach would be attach the listener of mouseup to the window object doing something like this

$(window).on('mouseup', on_mouse_up );

and then, from the mouse position calculating the right spot.

function on_mouse_up( e ) {
    // Get the mouse position
    x = e.pageX;
    y = e.pageY;

    // Calculate the spot from the mouse position

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download