Matilda Yi Pan
Matilda Yi Pan

Reputation: 658

jquery combined click and hover function only works for click, not working for hover

My question is fairly simple but confusing. I have combined "click" and "hover" by using .on(), but the function is only firing when click, not hover.

JS:

    var hoverElem = null;
    $("table tbody tr td").on('click hover', function(e){
        alert("TDDDDD!!!!");

    });

The html part is a simple html table.

Does anyone know why?

Upvotes: 0

Views: 893

Answers (4)

cleaver
cleaver

Reputation: 370

There's just slightly different syntax for multiple events in the same on().

$( "table tbody tr td" ).on({
  click: function() {
    alert("TDDDD!!");
  }, 
  hover: function() {
    alert("TDDDD!!");
  }
});

This has repeated code, so just create a function:

alertFunc = function() {
  alert("TDDDD!!!");
};
$( "table tbody tr td" ).on({
  click: alertFunc, 
  mouseover: alertFunc
});

See the example for handling multiple events at: http://api.jquery.com/on/ (Look for: "Example: Attach multiple event handlers simultaneously using a plain object.")

Upvotes: 0

Sameera Thilakasiri
Sameera Thilakasiri

Reputation: 9498

Just wondering how click and hover working together, because when you mouseover itself event is fired.

this is the example using fiddle

var hoverElem = null;
$("div").on('click mouseover', function(e){
    alert("TDDDDD!!!!");

});

Upvotes: 1

manishie
manishie

Reputation: 5322

I don't know WHY it doesn't work when you put the hover in jQuery on, but if you use jQuery hover instead, it works. Click the button below to run the code.

$(function() {
  function my_function(e) {
    alert("TDDDDD!!!!");
  };

  $("table tbody tr td").on('click', function(e) {
      my_function(e);
    })
    .hover(function(e) {
      my_function(e);
    });


});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>test</td>
  </tr>
</table>

Upvotes: 0

jvv
jvv

Reputation: 21

I think you have to use 'mouseover' rather than 'hover', which isn't listed in the events: http://api.jquery.com/Types/#Event. There is a separate hover function, though: http://api.jquery.com/hover/.

Upvotes: 0

Related Questions