1

I have the following jQuery code that listens to a checkbox:

$('.vimeo-pro-checkbox').change(function() {
  $('.vimeo-pro-panel').slideToggle();
});

Except it only works if I do something like the following:

// create a function
var init_vimeo_pro_checkbox = function() {
  $('.vimeo-pro-checkbox').change(function() {
    $('.personal-vimeo-pro-panel').slideToggle();
  });
}

var ready = function() {
  init_vimeo_pro_checkbox();
};

// call the function
$(ready);

So my question is why doesn't my first version just work? I mean it's inside a jquery function block: $().

I was under the impression the first version would just work, that jQuery would pick up my checkbox.

stephenmurdoch
  • 34,024
  • 29
  • 114
  • 189

4 Answers4

4

The reason why your first statement doesn't work, is because jQuery is simply not loaded / parsed until then.

When the browser receives your HTML document to parse it starts parsing the HTML Dom first, and then it starts loading the referenced files asynchronously.

This makes it possible that you may have code in your javascript inside the HTML document, that references a function that is defined somewhere in a referenced file that wasn't parsed yet. Therefor the browser throws an error and tells you the function is unknown.

This is why you use the $(document).ready(); handler (or short $();). This makes sure that all referenced files / scripts are loaded and parsed before your code gets executed.

RononDex
  • 4,143
  • 22
  • 39
3

You need to wrap the first code like this $(function(){...});

$(function () {
    $('.vimeo-pro-checkbox').change(function () {
        $('.vimeo-pro-panel').slideToggle();
    });
});
Anton
  • 32,245
  • 5
  • 44
  • 54
  • I cannot see difference between your code and marflar. It is shorter but should be same – Piotr Stapp Jan 24 '14 at 09:35
  • @Garath the difference is that the first code is not wrapped with a dom ready handler. OP is wondering why the first code does not work, and the second does. – Anton Jan 24 '14 at 09:35
2

are you loading the box dynamically?

in order for any eventhandlers to be bound to an element it must be present in the DOM before that code is hit.

If you are not sure try something like

$(function () {
    $('body').on('change','.vimeo-pro-checkbox',(function () {
        $(this).slideToggle();
    });
});
Ian Wood
  • 6,515
  • 5
  • 34
  • 73
1

In my opinion problem is that $('.vimeo-pro-checkbox') does not evaluate correctly before document ready. The element .vimeo-pro-checkbox just doesn't exist

Piotr Stapp
  • 19,392
  • 11
  • 68
  • 116