Wednesday, April 3, 2013

jQuery noConflict()

We all know that jQuery use $ sign as a shortcut for jQuery. There are other javascript framework also that use $sign as shortcut. So,what if one wants to use another framework also, while still using jQuery and that too uses $sign as a shortcut.

In such a situation if you use both the frameworks simultaneously this may result in that your script does not work.

For such situations jQuery team has implemented noConflict() method. The noConflict() method releases the hold on $ symbol so that other scripts may use it and instead of it you can use the full name. For Example:

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>

<script>
$.noConflict();
jQuery(document).ready(function(){
jQuery("button").click(function(){
      jQuery("p").text("jQuery is still working!");
});
  });
</script>
</head>
<title>Document1</title>
<body>
<p>Hello World</p>
<button>Click Me</button>
</body>
</html>

The noConflict() method returns a reference to jQuery which you may use to create your own shortcut very easily. For example:

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>

<script>var name = $.noConflict();
name(document).ready(function(){
      name("p").text("jQuery is still working!");
  });
</script>
</head>
<title>Document1</title>
<body>
<p>Hello World</p>
<button>Click Me</button>
</body>
</html>
Here I, saved the reference returned by noconflict() method in a variable named name and further used it as just another shortcut symbol instead of $.

No comments:

Post a Comment