From the documentation I've found this example:
We can animate any element, such as a simple image:
<div id="clickme"> Click here </div> <img id="book" src="book.png" alt="" width="100" height="123" />
With the element initially shown, we can hide it slowly:
$('#clickme').click(function() { $('#book').fadeOut('slow', function() { // Animation complete. }); });
I remember from 5 years ago, that you should NEVER ever refer to any element until it was defined. Does this rule still apply? So I would have to put all that code in the footer of my web page? Or can I put it in a separate file and import it in the footer? What's best practice?
jQuery code is implemented as part of JavaScript scripts. To add jQuery and JavaScript to your web pages, first add a <script> tag that loads the jQuery library, and then add your own <script> tags with your custom code.
A simple solution for anyone learning jQuery is to always declare your jQuery code inside the document ready function. This is to ensure that all of the html page elements also known as the DOM (Document Object Model) have loaded before any jQuery code is run.
To avoid multiple server requests, group your JavaScript files into one. Whatever you use for performance, try to minify JavaScript to improve the load time of the web page. If you are using single page application, then group all the scripts in a single file.
Using the script tag to include an external JavaScript file The script tag should either be included between the <head> tags or just before the closing <body> tag in your HTML document. JavaScript is often placed before the closing body tag to help reduce the page loading time.
The recommended way of doing this is putting all initialization code into $(document).ready
, like so:
$(document).ready(function() {
$('#foobar').click(function(event) { alert("You Clicked Me!"); });
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With