Jhansi
Jhansi

Reputation: 19

How can I prevent a JavaScript file from conflicting with another?

I have 2 scripts running on a site I am developing and one is conflicting with the other

The second one will only work if the first one is missing.so I don't know what the problem is.

You can see this link.

http://electionsguru.in/mfc_new/newkursplan.php?id_shop=35

in this page having Preview title that is on 3rd section,in that part if you click on any title light box will appear but left menu drop down script does not work and conflicting with light box script.

Upvotes: 0

Views: 1616

Answers (1)

bphillips
bphillips

Reputation: 459

Depending on how large your script is, using a Namespace is typically a good way to eliminate conflicts.

The 2 most common ways to introduce are:

var ns = ns || {};
ns.ondocready = function(){/*your declaration here*/};
ns.onsomeotherfunct = function(arg){/*your declaration here*/};

or

var othernamespace = {
  publicvar:'something available to all namespaced functions',
  ondocready:function(){/*your declaration here*/},
  someotherfunction:function(arg){/*your declaration here*/}
};

Then call the functions within the named object (e.g. namespace)

ns.ondocready();
othernamespace.someotherfunction('test');
othernamespace.publicvar = 'available to functions within namespace by referencing with "this" keyword';

The only caveat is to remember that when using the "this" keyword to reference variable or functions within the object, it may conflict with jQuery "this" keyword. To avoid, set to a variable within your function.

var ns1 = {
  islive : false,
  docheck : function(){
    var ns = this; //--set scope to variable for access to prevent conflict within jQuery functions where this keyword is referenced
    if(this.islive){/*conditional declaration*/};
  }
}

Upvotes: 1

Related Questions