Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery functions are not working without document.ready why.?

Tags:

jquery

//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);
   });
});
like image 268
GAURAV GUSAIN Avatar asked Feb 11 '23 14:02

GAURAV GUSAIN


2 Answers

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
    });
});

Fiddle: https://jsfiddle.net/BenjaminRay/j7kr21aj/

like image 112
Benjamin Ray Avatar answered Feb 13 '23 05:02

Benjamin Ray


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);
   });
});
like image 20
4EACH Avatar answered Feb 13 '23 04:02

4EACH