Such simple code, why isn't it working? When the page loads, it should display an alert box that reads "ready".
<!DOCTYPE html>
<html>
<head>
<title>
Title
</title>
<script type="text/javascript">
$(document).ready(function() {
alert("ready");
});
</script>
</head>
<body>
Content
</body>
</html>
I feel like it's something incredibly obvious, but I'm at a point where I can't think straight.
I've tried both in the latest versions of Chrome and Firefox.
$( document ). ready()A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ). ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.
load() event is that the code included inside onload function will run once the entire page(images, iframes, stylesheets,etc) are loaded whereas the $(document). ready() event fires before all images,iframes etc. are loaded, but after the whole DOM itself is ready.
The ready() method is used to make a function available after the document is loaded. Whatever code you write inside the $(document ). ready() method will run once the page DOM is ready to execute JavaScript code.
The $(document). ready() is a jQuery event which occurs when the HTML document has been fully loaded, while the window. onload event occurs later, when everything including images on the page loaded.
Where's your jquery ref?
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
I had this problem, but jQuery was referenced. I had accidentally written the previous script tag as a self closing tag when moving my javascript to an external file:
<script type="text/javascript" src="/wherever/whatever.js" />
<script type="text/javascript">
$(document).ready(function(){ /* not hit */ });
</script>
The external reference tag can't be self-closing. It should read <script type="text/javascript" src="/wherever/whatever.js"></script>
You forgot to include jQuery, so $
is undefined.
One glance at the JS console in chrome was all it took to figure out. Whenever something JS wont go, your first check should always be the console to look for an error. Usually this will tell you exaxtly what's up.
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