Max Frai
Max Frai

Reputation: 64266

JavaScript and DOM

I can't understand such situation:

I have a site template and in header there is code:

$(document).ready(function () {
    $('#header').corner();
    ...
}

corner() is just a jQuery-plugin function. But the problem is:

("#header") is null
    $('#header').corner();

It works at main page, but at another one (with the same template) - doesn't work.

To view everything in action, look at this page. You will see header (blue top div) rounded and there aren't any errors in firebug console. Now go to this page. Everything works too, but this time that's not the main page (it still uses same template file).

And the third page, the error appears there but still the same template. What's wrong?

Upvotes: 1

Views: 109

Answers (4)

Eric
Eric

Reputation: 97555

As mentioned, you have a name collision with Prototype. The easiest way to fix this is:

jQuery(function($) {
    $('#header').corner();
    ...
});

Upvotes: 0

jAndy
jAndy

Reputation: 235962

If you type into your console:

$.toString();

You'll see that some script, somewhere overwrites the jQuery shortcut $. That is most likely the reason for that error. To solve that, create a wrapper context for your whole code:

(function( $ ) {
    $(document).ready() {
        $('#header')....
    });
}(jQuery));

That will guarantee that the $ symbol now refers the jQuery object, within that function context.

Upvotes: 1

Tigraine
Tigraine

Reputation: 23648

A good solution is to use namespacing for your scripts like this to avoid naming conflicts as Quentin already mentioned.

You can still use $ by doing the following:

(function($) {
  //your code goes here and can use $ as jQuery without interfering with Prototype
} (jQuery));

This way you never have to use $ directly while being able to selectively use $.

Upvotes: 1

Quentin
Quentin

Reputation: 943099

The problem is that $ is a stupid name a for a function.

On the third page, $ is defined by jQuery and redefined by Prototype. You are getting conflicts.

Start by rewriting all your jQuery stuff to use jQuery instead of $ and call noConflict.

Upvotes: 7

Related Questions