Use ready()
to make a function available after the document is loaded:
Toggle between slide up and slide down for a p element.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script>/*from w w w.j av a2 s . co m*/ <script> $(document).ready(function(){ $("button").click(function(){ $("p").slideToggle(); }); }); </script> </head> <body> <p>This is a paragraph.</p> <p>This is a paragraph.</p> <p>This is a paragraph.</p> <button>test</button> </body> </html>
The ready event occurs when the document object model (DOM) has been loaded.
Two syntaxes can be used:
$(document).ready(function)
The ready()
method can only be used on the current document, no selector is required:
$(function)
Parameter | Optional | Description |
---|---|---|
function | Required. | function to run after the document is loaded |