When you first start with jQuery, you will probably run into something that looks like this:
$(document).ready(function(){/*... do stuff */});
So let’s break this down, because we’ve seen most of it already.
First $
. This is actually a legal variable in JavaScript. jQuery isn’t the only who uses it, but it’s most commonly associated with them. You can also use jQuery
. This is a function that has been assigned to a variable. This makes it shorter/faster to write, and in theory, smaller code to make it faster as well.
In its parameter list is the CSS selector to select what you want. Usually this will be in a string, but for document
, you can just use its name.
The .ready()
is an event handler. It means, when the JavaScript engine has read and parsed the document. (Remember, this is part of how JavaScript works.) Once it is parsed and put into memory, the Document Object Model, or DOM, can be used and manipulated by JavaScript.
Inside the event handler, you have passed it an anonymous function (remember, JavaScript can do this), which is what will execute when the DOM is ready.
What Can You Put in There
Inside the anonymous function, you can put any legal JavaScript code. We often use this to assign other event handlers, modify the HTML code (DOM) that already exists, etc.
Consider the following HTML page, with the associated CSS:
<!DOCTYPE html>
<html>
<head>
<style>
nav {
border-bottom: 2px solid #999;
margin-bottom: 10px;
padding: 10px 0 15px 0;
}
.demo {
font-size: 20px;
font-weight: bold;
padding: 10px;
border-radius: 5px;
border: 1px solid #444;
text-decoration: none;
}
</style>
</head>
<body>
<nav>
<a href="#">Demo</a>
</nav>
<a href="#">Standard Link</a>
</body>
</html>
Obviously, there is not a lot of content, but it shows the basics of what we want to see. Specifically, we have two links, and a class that is not used anywhere. But, we’re going to assign that class once the DOM is ready, and it should happen fast enough, that the user will never see.
<script src="https://code.jquery.com/jquery-3.7.1.min.js"
integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
$('nav a').addClass('demo');
});
</script>
When we execute this code, the class is assigned to the link in the nav section of the HTML, because we specified that with our selector. We can select any element on a webpage that we want for jQuery’s use, by using CSS3 selector.
While it might be easier to just this example in the HTML code, this example shows us how to make changes based upon other factors, and that is where $(document).ready()
is so powerful. We will assign event handlers, call external code, and more, all while we get things ready for the end user.
jQuery – When the Dom is Ready was originally found on Access 2 Learn
2 Comments
Comments are closed.