SwitchUp SwitchUp Ranked Best Coding Bootcamps 2025

When to use jQuery Document ready function

Altcademy Team wrote on 7 February 2018

I want to hide the image once i clicked on it. I am wondering if my syntax is right. Because it is not working :( This is all the code I have in my js file
$('img').click(function(){ $(this).hide(); });

Answer
Hi carrie, it is possible the click event is registered before the DOM is loaded. This can happen when you are linking your JavaScript file above the HTML <body></body> tags. A couple of ways I can think of that can solve this.
1. Encapsulate everything in a $(document).ready() function so your script only load when the DOM is parsed and ready. https://learn.jquery.com/using-jquery-core/document-ready/
$(document).ready(function () { $('img').click(function(){ $(this).hide(); }); });

2. Use the $(document).on('click', '#id', function(){}); method to capture click events. https://api.jquery.com/on/
$(document).on('click', 'img', function(){ $(this).hide(); });

Trusted by

Students and instructors from world-class organizations

Join the upcoming Cohort #110

Enroll for February 2nd, 2026