Forbes magazine logo Ranked Best Coding Bootcamps 2023

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

Imperial College London
Carnegie Mellon University
City University of Hong Kong
Hack Reactor
Cisco Meraki
University of Oxford
Swift
Bazaarvoice
Waterloo
Uber
AtlanTech
Tumblr
Boston College
Bombardier Aerospace
University of St. Andrews
New York University
Minerva Schools at KGI
Merrill Lynch
Riot Games
JP Morgan
Morgan Stanley
Advanced Placement®
Google
KPMG
The University of Hong Kong
University of Toronto
SCMP
Moat
Zynga
Hello Toby
Deloitte
Goldman Sachs
Yahoo
HSBC
General Assembly
Tesla
McGill University
Microsoft

Join the upcoming Cohort #96

Enroll for December 2nd, 2024