4

//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);
   });
});
4EACH
  • 2,132
  • 4
  • 20
  • 28
GAURAV GUSAIN
  • 41
  • 1
  • 3
  • Did you see this answer? http://stackoverflow.com/questions/20819501/jquery-click-event-not-working-for-dynamically-created-button/20819663#20819663 – Majid Golshadi Mar 22 '15 at 18:04

3 Answers3

3

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/

Benjamin Ray
  • 1,855
  • 1
  • 14
  • 32
  • 1
    That's not exact. The code will be executed after the page is READY, not LOADED. Ready means : the end of the HTML file has been reached and the DOM has been created. Loaded means : all resources, including scripts and images, are fully loaded into view. That means the script won't work if jQuery hasn't finished loading. That can happen if jQuery's script tag is placed after the script using it. – Jeremy Thille Mar 22 '15 at 16:40
  • @Jeremy Thille Thanks for clarifying and explaining. I've updated the wording describing when the .ready() function occurs. – Benjamin Ray Mar 22 '15 at 17:24
3

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);
   });
});
4EACH
  • 2,132
  • 4
  • 20
  • 28
2

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.

lin
  • 17,956
  • 4
  • 59
  • 83
Estus Flask
  • 206,104
  • 70
  • 425
  • 565