//This code is not working until we are doing using Document.ready
$('.a').on('click',function(){
$('.a').fadeOut(200);
});
$(document).ready(function () {
$('.a').on('click', function() {
$('.shad').fadeIn(1000);
});
});
//This code is not working until we are doing using Document.ready
$('.a').on('click',function(){
$('.a').fadeOut(200);
});
$(document).ready(function () {
$('.a').on('click', function() {
$('.shad').fadeIn(1000);
});
});
Any JavaScript outside of a function is executed in the order in which it appears in the page. When you call $('.a') too early, those elements may not exist yet and jQuery may not have been loaded yet.
Anything inside $(document).ready(function() { ... } will be executed after the full page is READY, by which point all of the class 'a' elements will now exist on the page. (See comment from Jeremy Thille for clarification on "ready" vs "loaded".)
HTML:
<div class="a">click me</div>
<div class="shad">SHAD!</div>
JS:
$(document).ready(function () {
$('.shad').hide(); // Hide the element on load
$('.a').on('click', function () {
$('.shad').fadeIn(1000); // Fade in on click
});
});
It caused by trying to creating an event on element that doesn't exists in DOM. use $(document).ready to make sure that elements existing in your DOM.
$(document).ready(function () {
$('.a').on('click', function() {
$('.a').fadeOut(200);
$('.shad').fadeIn(1000);
});
});
This happens because $(document).ready(function () { ... })
(usually the shortcut (function () { ... })
is used instead) runs when the DOM is ready for manipulation (hence the function's name). Before this moment DOM elements you're referring in jQuery selectors aren't available. Note that you can manipulate a DOM element if <script>
element goes after it (e.g. at the end of <body>
).
As jQuery documentation says,
The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code.