Home > Web Front-end > JS Tutorial > body text

How to Alternate Function Calls on Click Events?

Mary-Kate Olsen
Release: 2024-11-08 16:31:02
Original
301 people have browsed it

How to Alternate Function Calls on Click Events?

Alternating Function Calls with Click Events

Question:

How can I execute different functions when an element is clicked, alternating between them with each successive click?

Answer:

jQuery offers an alternate version of the .toggle() method specifically designed for this purpose, although it has since been deprecated. There are alternative approaches, such as creating a custom plugin that provides the desired functionality.

Using the Deprecated .toggle() Method:

$('#element').toggle(function() {
  // Function 1
}, function() {
  // Function 2
});
Copy after login

Custom Plugin:

(function($) {
  $.fn.clickToggle = function(func1, func2) {
    var funcs = [func1, func2];
    this.data('toggleclicked', 0);
    this.click(function() {
      var data = $(this).data();
      var tc = data.toggleclicked;
      $.proxy(funcs[tc], this)();
      data.toggleclicked = (tc + 1) % 2;
    });
    return this;
  };
}(jQuery));

$('#element').clickToggle(function() {
  // Function 1
}, function() {
  // Function 2
});
Copy after login

Notes:

  • The custom plugin can be used for any event, not just click.
  • It accepts an arbitrary number of functions to be executed in alternation.
  • The deprecated .toggle() method may cause performance issues in complex scenarios.

The above is the detailed content of How to Alternate Function Calls on Click Events?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!