Asherlc
Asherlc

Reputation: 1161

jQuery selector (from within a plugin) works in jsFiddle, but not real page?

For the life of me, I can't figure out why trying to select an element via the jQuery global object works in jsFiddle, but not on a normal page.

HTML

JSFiddle

I've been wrestling with this problem for some time building a larger plugin, and eventually narrowed it down to this weird discrepancy.

Is there something I'm missing here?

Upvotes: 0

Views: 106

Answers (1)

gen_Eric
gen_Eric

Reputation: 227260

This is happening because on your page you are not waiting for the DOM to be ready before running $.salsaform();.

jsFiddle has your code in an onLoad handler, so it runs once the DOM is ready.

Change your script to this:

(function ($) {
  $.salsaform = function () {
    console.log($('#foo'));
  };
})(jQuery);

$(function(){
    $.salsaform();
});

The $(function(){...}) runs your code after the DOM is ready.

Upvotes: 4

Related Questions