Sachindra Sachindra - 7 days ago 6
Javascript Question

javascript conflict

why does some javascripts come in conflict with some other ones? I mean I had been using javascript code for image gallery and then tried to get the text watermark in jquery. Why is that after using the jquery, the gallery totally disappeared? there was no common ids that I used inthe two scripts. Any reason for that?

Answer

As Mathias has correctly pointed out, the most likely problem is that your other library is also using the $ symbol -- when you added jQuery to the page it overwrote the old $ variable with its own $ ... and your first javascript library ceased to work. The solution is to call jQuery.noConflict() to restore the $ variable to the first library. You will still be able to use jQuery plugins -- you will just need to update example scripts that use $ to use jQuery instead. Thus $("#my_content").css({color: "red"}); would become jQuery("#my_content").css({color: "red"});

Alternately, you can assign the jQuery object to another variable object in this manner:

$jq=jQuery.noConflict(); //From now on jQuery can be called with the $jq function

or you can use it within a closure:

(function($) {
    // $ in here will map to jQuery
    //outside of this code $ will map to your other library's $
})(jQuery.noConflict());
Comments