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?
6
  • api.jquery.com/toggle-event "It is relatively straightforward to implement the same behavior by hand". Commented Aug 1, 2018 at 9:40
  • Also: stackoverflow.com/a/25150375/2181514 Commented Aug 1, 2018 at 9:41
  • and: stackoverflow.com/search?q=jquery+toggle+event Commented Aug 1, 2018 at 9: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. Commented Aug 1, 2018 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. Commented Aug 1, 2018 at 10:52

1 Answer 1

-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");
});
Sign up to request clarification or add additional context in comments.

1 Comment

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...)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.