1

If we have 2 functions we want to execute alternatively, one at mouseover and the other at mouseout, we can do that easily in jQuery:

var firstFunc = function() {
  console.log("first");
}

var secondFunc = function() {
  console.log("second");
}

$('.class-name').hover(firstFunc, secondFunc);
.class-name {
  display: inline-block;
  padding: 5px 15px;
  cursor: pointer;
  font-family: Arial, sans-serif;
  font-size: 14px;
  border: 2px solid #069;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="class-name">Hover me</div>

Since the deprecation of toggle(), we can not use it to trigger the two functions alternatively, on click event.

In fact, I want to use both: hover on desktops and click on mobile devices.

Questions:

  1. What shall we use instead?
  2. What would be helpful if used in a manner similar to the hover() method, without the use of an if clause?
Razvan Zamfir
  • 4,209
  • 6
  • 38
  • 252
  • http://api.jquery.com/toggle-event/ "*It is relatively straightforward to implement the same behavior by hand*". – freedomn-m Aug 01 '18 at 09:40
  • Also: https://stackoverflow.com/a/25150375/2181514 – freedomn-m Aug 01 '18 at 09:41
  • and: https://stackoverflow.com/search?q=jquery+toggle+event – freedomn-m Aug 01 '18 at 09:42
  • Since "I want to use both: hover on desktops and click on mobile devices", I believe my question is not a duplicate. It would be useful to post an answer with the exact solution I have applied. – Razvan Zamfir Aug 01 '18 at 10:09
  • You can't quietly change the question then say, "but I said this...". You could say you've updated the question and don't believe that you have the skill to rework the provided answer to match your scenario. – freedomn-m Aug 01 '18 at 10:52
  • Your edit **completely changes the question** - you might be better off asking a *new* question that includes *all* the details. – freedomn-m Aug 01 '18 at 10:53

1 Answers1

-1

Better way is to create separate events.

$(document).on('mouseover', '.class-name', function () {
    console.log("first");
});

$(document).on('mouseout', '.class-name', function () {
    console.log("second");
});
Jay Raj Mishra
  • 110
  • 2
  • 9
  • 1
    Did you read the question? It's about using `.toggle` - the `.hover` was just there as an example of how simple this could be (and to confuse everyone...) – freedomn-m Aug 01 '18 at 09:46