Javascript conflict

why do some javascripts conflict with some others? I mean, I used javascript code for image gallery and then tried to get text watermark in jquery. Why did the gallery completely disappear after using jquery? there were no common identifiers that I used in two scenarios. Any reason for this?

+3
source share
3 answers

As Mathias correctly pointed out, the most likely problem is that your other library also uses the symbol $- when you added jQuery to the page, it rewritten the old variable $with its own $... and your first javascript library stopped working. The solution is to call jQuery.noConflict () to restore the variable $in the first library. You can still use jQuery plugins - you just need to update the sample scripts that you use $for use jQuery. Thus $("#my_content").css({color: "red"});willjQuery("#my_content").css({color: "red"});

Alternatively, you can assign a jQuery object to another variable object as follows:

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

or you can use it in closing:

(function($) {
    // $ in here will map to jQuery
    //outside of this code $ will map to your other library $
})(jQuery.noConflict());
+3
source

Sometimes people can use global variables in their packed javascript. If you have two packages that use the same global variable, then obviously there will be problems. To solve this problem, try creating a closure of each package code. Without seeing the code, I am not 100% to make it work, but here is an example:

// gallery.js
var textTitle = "Image gallery";

function getGalleryTitle() { return textTitle; }


//////////////
// watermark.js

var textTitle = "Watermark";


alert(getGalleryTitle()); // "Watermark"  :(

Now with a closure created using anonymous functions:

(function() {
    var textTitle = "Image gallery";
    function getGalleryTitle() {
        return textTitle;    // this will always be "Image gallery"
    }
})();

(function() {
    var textTitle = "Watermark";    // won't conflict with any other code.
})();

The disadvantage is that you can no longer access these variables and functions globally (for example, through the built-in event handlers).

+1
source

Source: https://habr.com/ru/post/1755674/


All Articles