Home  >  Article  >  Web Front-end  >  Very practical jQuery toggle() method

Very practical jQuery toggle() method

巴扎黑
巴扎黑Original
2017-06-29 10:51:051151browse

Example

Switch different background colors:

$("p").toggle(
  function(){
  $("body").css("background-color","green");},
  function(){
  $("body").css("background-color","red");},
  function(){
  $("body").css("background-color","yellow");}
);

Definition and usage

toggle() method is used to bind two or more event handlers DeviceFunction, to respond to the click event of the selected element in turn.

This method can also be used to switch the hide() and show() methods of the selected element.

Bind two or more functions to the Toggle event

When the specified element is clicked, switch between two or more functions in turn.

If more than two functions are specified, the toggle() method will toggle all functions. For example, if there are three functions, the first click will call the first function, the second click will call the second function, and the third click will call the third function. The fourth click calls the first function again, and so on.

Syntax

$(selector).toggle(function1(),function2(),functionN(),...)

Try it yourself

Parameters Description
function1() Required. Specifies a function to run when the element is clicked every even number of times.
function2() Required. Specifies a function to be run every odd number of times the element is clicked.
functionN(),... Optional. Specify other functions that need to be switched.


Switch Hide() and Show()

Check whether each element is visible.

Run show() if the element is hidden. If the element is visible, the element hide(). This creates a switching effect.

Syntax

$(selector).toggle(speed,callback)

Try it yourself

##callback
Parameters Description
speed

Optional. Specifies the speed of hide/show effects. The default is "0".

Possible values:

  • milliseconds (e.g. 1500)

  • "slow"

  • "normal"

  • "fast"

Optional. Function executed when the toggle() method completes.

To learn more about callback, please visit our Callback function tutorial.

Show or hide elements

Specifies whether to only display or hide all matching elements.

Syntax

$(selector).toggle(switch)

Try it yourself

ParametersDescription
switch Required. A Boolean value that specifies whether toggle() should only show or hide all selected elements.

  • true - Show the element

  • false - Hide the element

The above is the detailed content of Very practical jQuery toggle() method. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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