$(document).ready(function() {
// Code inside this block will only execute after the DOM is fully loaded.
// Example 1: Alert when the page is ready
alert("The page is fully loaded!");
// Example 2: Modify HTML elements
$('h1').text('Welcome to My Website');
$('p').html('This is an updated paragraph.');
// Example 3: Event handling
$('#myButton').click(function() {
alert('You clicked the button!');
});
});
In this example, the JavaScript code inside the $(document).ready()
function will run once the DOM is ready, ensuring that any modifications to the HTML elements or event handling are done only when the elements are available and accessible.
Remember to include the jQuery library before your script file. The script file (script.js
) in this example is placed at the end of the body tag to ensure that it is loaded after the rest of the content, including the DOM elements it will interact with.