Edgar Navasardyan Edgar Navasardyan - 1 month ago 8
jQuery Question

Removing mouseover event issue in case of embedded tables

Best described as example in this Fiddle
My goal is to show the crosses when the user hovers above the tables. The problem is that the mouse-over event behavior is very strange, and it is fired for all of the children. This is the follow-on to my previous question, and here I tried to be more specific about the case.

Any ideas ?

$(function() {
$(document).on('mouseover', 'table tbody tr', function (e) { change_editor_icon_visibility($(this), true)});
$(document).on('mouseout', 'table tbody tr', function (e) { change_editor_icon_visibility($(this), false)});
});


function change_editor_icon_visibility(row_obj, mode)
{
var elem = row_obj.find('tr:hover').length ?
row_obj.find('tr:hover:last') : row_obj;
elem.find('td span.zeon-edit-pencil').toggle(mode);
}

Answer

Use :first pseudo selector

:first Selector Selects the first matched DOM element.

$(function() {
  $(document).on('mouseover', 'tr', function(e) {
    e.stopPropagation();
    change_editor_icon_visibility($(this), true)
  });
  $(document).on('mouseout', 'tr', function(e) {
    e.stopPropagation();
    change_editor_icon_visibility($(this), false)
  });
});


function change_editor_icon_visibility(row_obj, mode) {
  row_obj.find('td span.zeon-edit-pencil:first').toggle(mode);
}
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<style>
  .zeon-remove-sign {
    display: none;
  }
</style>

<table>
  <tbody>
    <tr id='1'>
      <td><span class='glyphicon glyphicon-remove zeon-edit-pencil zeon-remove-sign'></span>AAAAAAA
        <table>
          <tbody>
            <tr id='2'>
              <td>
                <span class='glyphicon glyphicon-remove zeon-edit-pencil zeon-remove-sign'></span>
              </td>
              <td>BBBBBBBBBBB</td>
            </tr>
            <tr id='3'>
              <td>
                <span class='glyphicon glyphicon-remove zeon-edit-pencil zeon-remove-sign'></span>
              </td>
              <td>CCCCCCCCCCC</td>
            </tr>
          </tbody>
        </table>
      </td>
    </tr>
  </tbody>
</table>