I’m having some trouble using trying to determine if a mouse click is occurring in a table cell which is directly below an element with id=#blankElement.
The event handlers work fine for clicking cells which are to the right or left of the specified element but if any other cells are clicked I get the ‘Cell is above’ alert ..
$(function () {
var $tbl = $('<table border="1">').attr('id', 'grid');
var $tbody = $('<tbody>').attr('id', 'tableBody');
for (var i = 0; i < $("#numOfPieces").val(); i++) {
var trow = $("<tr>"); // New row
for (var j = 0; j < $("#numOfPieces").val(); j++) {
$("<td>")
.text('Row : ' + i + ', Col: ' + j)
.appendTo(trow);
}
trow.appendTo($tbody);
}
$tbl.append($tbody);
$('table').remove();
$('body').append($tbl);
$('#grid tr:first td:last').prev().text("");
$('#grid tr:first td:last').prev().attr('id', 'blankElement');
});
// Event handler for clicking table cells
$('body').on('click', '#grid td', function(e) {
if ($(this).closest('td').next("#blankElement").length){
alert('Cell to the right');
}else if ($(this).closest('td').prev("#blankElement").length){
alert('Cell to the left');
}else if ($(this).parent().next().children().eq($(this).index())){
alert('Cell is above');
}
});
There you go, folks, fiddle: http://jsfiddle.net/yQk28/23/
There are number of things wrong with your code:
eq() acts like a selector and will return array of elements. when
nothing is matched it will return [], which still evaluates to true.
you are selecting all children and not only the element that you are looking for (children() acts as $() – you can pass additional selectors and it will filter children for you)
Take a look at the fiddle it’s pretty straight forward
Code: