conflict between two jquery plugins with same function name - javascript

I am working in a large site that has 2 conflicting jquery plugins included for doing autocmplete.
1) jquery.autocomplete.js (not part of jquery ui) that does :
$.fn.extend({
autocomplete: function ...
2) jquery.ui.autocomplete.js (from the latest jquery ui library), that also uses the autocomplete keyword.
$.widget( "ui.autocomplete", { ...
Is there a way to specify that i am using only the second, jquery.ui widget
when calling
$( "#tags" ).autocomplete ...
without changing the 2 files?

As the second autocomplete is using the $.Widget method of registering itself with jQuery it'll be easiest to change the behaviour of the in-house one.
You won't be able to load both of them without making some sort of change to the jQuery object between the two script loads because they'll just conflict with (or overwrite) each other.
I would try this:
<script src="jquery.autocomplete.js"> </script>
<script>
// rename the local copy of $.fn.autocomplete
$.fn.ourautocomplete = $.fn.autocomplete;
delete $.fn.autocomplete;
</script>
<script src="jquery-ui.autocomplete.js"> </script>
Which will then make:
$().autocomplete()
use the jQuery UI version, and
$().ourautocomplete()
use your local version.

I tried to do it with the tabs function of jQuery UI, it should work the same for you.
A function is technically a js object, so you could simply rename it :
$.fn.tabs2 = $.fn.tabs;
delete $.fn.tabs;
$("#tabz").tabs2({});
Hope that helps!
Edit
Like Alnitak suggested, you also need to delete the previous function's name.
Also, I think .fn is required.

Related

AngularJS $ not working without including jquery

I have some jquery code using $ in my controller. When I include jquery in the page, then it works fine but when I remove jQuery then I get following error:
ReferenceError: $ is not defined
I read online that jquery has inbuilt small footprint jquery named jQlite then why I get the error:
$('.scrollProductPicker , .scrollTailoredSupport').click(function(){
$('html, body').animate({
scrollTop: $( $(this).attr('href') ).offset().top
}, 500);
return false;
});
in Angular JS angular.element is used as an alias for $ or "JQuery", which is part of jqlite and hence if you are using $ directly you need to add the reference of jQuery. more details you can find at this link Angular JS documentation
Looking up elements via selectors is not supported by jqLite.
jLite is avaiable here angular.element.
So you cannot do this:
angular.element("body"); //DOES NOT WORK!
However, you can do:
angular.element(document.body); //DOES WORK!
jLite has just a sub set of functions from jQuery.
#Ramesh & #ThiagoPXP has given the correct answers. But you can still make full use of Angular to select any elements like so:
angular.element(document.querySelectorAll("div.foo"));
// or
angular.element(document.querySelector("#my-page ul.bar"));
You can make your code simpler by registering them as methods in Angular:
angular.findAll = function(selector) {
return angular.element(document.querySelectorAll(selector));
}
And then you can write easily as:
angular.findAll("div.foo");
// or
angular.findAll("#my-page ul.bar");
Or simpler (to use syntax like jQuery):
window.$ = function(selector) {
return angular.element(document.querySelectorAll(selector));
}
$("#my-page ul.bar") // will work
But, if you do not include jQuery, Angular will use a small version of jQuery i.e. jqlite which will not have every method available as jQuery.
This is definitely good. but I want that smooth scroll feature. Couldn't use angular-smoothscroll directive as the link is outside of my angular app and the target anchor is inside the angular app. I ended up with using vanilla javascipt for smooth scroll

Jquery to find and replace script line in header?

I have a script src for a deprecated version of JQuery which I cannot control (controlled externally via a CMS, not cross-domain, just no access to changing it) and I'd like to change the script src to a newer version of Jquery.
Old code:
<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
Replace with:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Once an external script has loaded, it can't be removed as it's already loaded into memory, so changing the source would just load another version of jQuery without removing the first version, so you'd have two versions of jQuery, creating a conflict, and in many cases nothing will work.
There is a workaround if you absolutely have to:
$(function() {
$j_142 = $.noConflict(true);
$j_142.getScript('//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js', function() {
$j_191 = $.noConflict(true);
});
});
FIDDLE
now you have two versions of jQuery mapped, and to use them you'd do:
$j_191('#selector')
of course, this would cause issues with code already written, but you could probably get away with just mapping the second script to a new variable or something ?
EDIT:
You could use a closure to map one of those values back to the dollarsign within the closure:
(function($) { //anonymous self invoking function
// now you could use the dollarsign as normal
$(function() { // document ready function
});
})($j_191);
You can use
var oldJquery = document.querySelectorAll('script[src="js/jquery-1.4.2.min.js"]');
oldJquery.src = "//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"
Once you do this, it will automotically will download coz it is live dom element. All changes should be reflected immediately.
But I would suggest that long term this is not good idea. what if CDN from google is down.
You might be in trouble. Just take precaution while doing this changes.
That easy, this is your code:
$("script[src='js/jquery-1.4.2.min.js']").attr('src', '//ajax.googleapis.com/ajax/libs/jquery/1.9.2/jquery.min.js');
This is example http://jsfiddle.net/rebeen/KwLM3/

How can I use Jquery to add 'hyphenate' class to P element not working in Joomla

I am developing a site using Joomla 2.5 and since I'm going to be handing it off to a client who is less than code savvy, I don't want to have to make them try to remember how to add class=hyphenate to every <p> when they add / update content.
I'm trying to use JQuery to do it but it doesn't seem to be working. Here is my code that should add the class:
<script type="text/javascript">
$("p").addClass("hyphenate");
</script>
Any input / help is - as always - appreciated!
Thanks,
Cynthia
If your script tag is placed before the p elements, you need to wait for the document to be ready - like this:
$(document).ready(function(){
$("p").addClass("hyphenate");
});
Shorthand version:
$(function(){
$("p").addClass("hyphenate");
});
Sidenote: when mixing libraries, global variables (like the $) can get out of hand. So make your own scope, ensuring that the $ is jQuery:
(function($){ // $ = jQuery
$(function(){
$("p").addClass("hyphenate");
});
})(jQuery);
Also your Jquery May Conflict with Joomla Mootools, to overcome you can use JQuery noConflict
var JQ=jQuery.noConflict();
JQ(document).ready(function(){
JQ("p").addClass("hyphenate");
});

jquery autocomplete this.source is not a function error

I've implemented autocomplete on an input field, but the box does not show up and firebug returns "this.source is not a function". I've used autocomplete on other fields of the same page without any problems. (two textarea's).
I'm using the following code to debug, same effect if I run from script file or Firebug command line.
var fakedata = ['test1','test2','test3','test4','ietsanders'];
$("#omschrijving").autocomplete(fakedata);
running jquery 1.4.2 and jquery ui 1.8.2, both minified versions.
Does anyone have an idea how autocomplete works fine on the textareas but causes this malfunctioning on inputs?
Error & Stack trace:
this.source is not a function
http://facturatie.autodealers.nl/dev/resources/js/jquery-ui-1.8.2.custom.min.js
Line 570
close(Object { name="a"})jquery....min.js (regel 570)
close(Object { name="a"}, Object { name="c"})jquery....min.js (regel 570)
response()
Answer is that the first parameter of the autocomplete should be an object containing the "source" property. This works
var fakedata = ['test1','test2','test3','test4','ietsanders'];
$("#omschrijving").autocomplete({source:fakedata});
If you were trying to use autocomplete from http://www.devbridge.com/projects/autocomplete/jquery/#demo, it now collides with the autocomplete method in jQuery UI. I had the same problem and later noticed that I could just use the jQuery UI implementation.
(NOTE: It appears that this page's documentation is wrong: http://docs.jquery.com/Plugins/Autocomplete#Setup)
If you use it with jQuery UI library it also has plugin named autocomplete. In this case you can use plugin alias devbridgeAutocomplete:
$('.autocomplete').devbridgeAutocomplete({ ... });
This solve the problem with jQuery UI collision
As Shelton stated, the version from devbridge.com (1.1.3) collides with jQuery UI (1.8.4). Got it working by making sure the devbridge version loads after jQuery UI's version.
Had similar problem for tagedit/autocomplete. It seems you also want to disable the autocomplete. Setting the source to false avoids these errors.
Solution:
options.autocompleteOptions.source = false;
Search at the end of jquery.autocomplete.js the following section:
Create chainable jQuery plugin:
$.fn.devbridgeAutocomplete = function (options, args) {....
This devbridgeAutocomplete is an alternative plugin to access to the same functionality using this lines:
if (!$.fn.autocomplete) {
$.fn.autocomplete = $.fn.devbridgeAutocomplete;
}
So.. you can use devbridgeAutocomplete instead of autocomplete or any name by changing this $.fn.devbridgeAutocomplete
in my case I had a second import of jquery which I didn't realize.
Something like:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.devbridge-autocomplete/1.2.27/jquery.autocomplete.min.js"></script>
// More code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script>
So be sure to import the autocomplete script after you initialized jquery.

Can I reset the name of jQuery's global object?

Let me give my question some context. I have a JavaScript widget. The widget includes a copy of jQuery from my site. This widget is placed on a third-party site. The widget parses a JSON feed and injects the contents into the DOM. Pretty simple stuff.
If the third-party page already has jQuery referenced and relies on jQuery plugins, conflicts could arise. Especially, when the third-party site references a different version of jQuery. $.noConflict() is useful, but the existence of plugins make it unreliable. From the $.noConflict() documentation:
If necessary, we can free up the
jQuery name as well by passing true as
an argument to the method. This is
rarely necessary, and if we must do
this (for example, if we need to use
multiple versions of the jQuery
library on the same page), we need to
consider that most plug-ins rely on
the presence of the jQuery variable
and may not operate correctly in this
situation.
To get around this issue, my idea is to reset the name of the jQuery global object. At the bottom of the jQuery source, there are these lines:
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
Could I refactor the lines to:
// Expose jQuery to the global object
window.myjQuery = jQuery;
I've removed the shorthand $ variable, and I've changed jQuery to myjQuery. Now my code can look like this:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>myjQuery</title>
<script type="text/javascript" src="myjquery-1.4.js" />
<script type="text/javascript">
// .ready() can alias the jQuery object
// I can pass $ and write code as normal
myjQuery(document).ready(function($) {
$('p').css('color', 'red');
});
// Fails
jQuery(document).ready(function($) {
$('p').css('color', 'blue');
})
// Fails
$(document).ready(function() {
$('p').css('color', 'green');
})
</script>
</head>
<body>
<p>myjQuery changed my color to red.</p>
</body>
</html>
Is this a good idea? I don't know the internals of the library enough to say for sure. I understand the library is basically a closure, so I'm guessing this approach is OK. Thoughts?
EDIT: I've accepted Doug's answer because he provided code which is almost identical to an example on the $.noConflict() documentation page. I didn't notice it before. Here is the example:
// Completely move jQuery to a new namespace in another object.
var dom = {};
dom.query = jQuery.noConflict(true);
// Do something with the new jQuery
dom.query("div p").hide();
// Do something with another library's $()
$("content").style.display = 'none';
// Do something with another version of jQuery
jQuery("div > p").hide();
It's not normally a good idea to edit a released file if you don't need to. I read your question, and this solution will work for your needs. Don't edit the jQuery core at all. Do this:
<script type="text/javascript" src="jquery-1.4.js"></script>
<script type="text/javascript">
// Revert $ and jQuery to their original values:
window.myjQuery = jQuery.noConflict(true);
(function($){
// Inside here, $ = myjQuery
$(document).ready(function(){
});
})(window.myjQuery);
</script>
The important thing is for your widget to include jQuery, then immediately call noConflict(true) and store it in a variable.
If you follow these steps exactly, it will not affect existing jQuery instances or plugins on the page. It will only give you a private version of jQuery in the variable myjQuery for your own plugin.
Secondly, using a self executing anonymous function, you can create a private scope for your widget where $ equals your included jQuery file.

Categories