mootools and jQuery conflict - javascript

I've got a simple form in a page that is loading Mootools and JQuery. JQuery is in no conflict mode, which seems like it ought to cause no problems.
There's a form element called "name"--
<input class="required" id="sendname" name="sendname" value="">
And I'm trying to attach a click event to it using Mootools to update something else when the name box is clicked:
$('sendname').addEvent('click', function(e){
// do stuff.
});
The problem is that the click event never gets added.
This error appears on load:
Uncaught TypeError: Cannot call method 'addEvent' of null
When I try to interact with the element in a js console, I get the following error:
> $('sendname').setProperty('value', 'test');
TypeError: Object sendname has no method 'setProperty'</strike>
EDIT: the previous was fixed by loading a newer Mootools. However, the click event still isn't functioning properly, though it throws no errors or warning.
This code works fine in almost any situation I've used it in. I assume there's some issue with jQuery conflicting, but the fact that the $ notation works seems to confirm that noConflict mode is operational. Any ideas?

You are targetting the element wrongly... I think this has nothing to do with a possible conflict.
In this case you need to add the hash for an id or a period for a class, like this:
$('#sendname').addEvent('click', function(e){
// do stuff.
});
Notice the # in #sendname

MooTools has Dollar Safe mode that automatically releases the $ to other libs as long as MooTools is loaded last.
If Dollar Safe mode is active, you need to use:
document.id('SomeElementID').someMethod()
What is happening in the example you are giving, is that you're using jQuery to select the element, and a MooTools method on the result. The thing is, jQuery returns the jQuery object which has no such 'addEvent' method on it. MooTools works on the actual elements so you need to select them with a MooTools query method first: $ == document.id or $$ == document.search
You can cache document.id to a var for convenience if you want:
var $M = document.id;
$M('sendname').addEvent(...)

As described in the comments to the OP, the issue was the load-order of the jQuery/Mootools scripts. The jQuery noConflict was being loaded too late, and causing problems. Please see jsfiddle -- http://jsfiddle.net/uSwzL/1/

Without any problem even loading jquery.js after other $ based library loaded:
<script>$=function(){alert('hell');}</script>
<script src="http://code.jquery.com/jquery-1.9.0.min.js"></script>
<script>
$.noConflict();
$();
alert(jQuery.trim(' hello '));
</script>
Even in php framework html template:
<script>
function on_doc_ready()
{jQuery(function($)
{$( "#sortable" ).sortable();
$( "#sortable" ).disableSelection();
}
);
}
function load_jquery_ui()
{var s2=document.createElement('scr'+'ipt');
s2.setAttribute('onload', 'on_doc_ready();');
s2.src='/app/idm/statics/jQuery/js/jquery-ui-1.10.0.custom.min.js';
document.getElementsByTagName('head')[0].appendChild(s2);
}
function load_jquery_after_mootools()
{var s1=document.createElement('scr'+'ipt');
s1.src='/app/idm/statics/jQuery/js/jquery-1.9.0.js';
s1.setAttribute('onload', '$.noConflict();load_jquery_ui();');
document.getElementsByTagName('head')[0].appendChild(s1);
}
load_jquery_after_mootools();
<script>

Related

Be sure that never have JQuery conflict

I need to create code which can be used as snipped for every site.
When I copy paste this code to any html in the world this should work:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript"> my_jQuery = $.noConflict(true);</script>
<script type="text/jscript">
my_jQuery(document).ready(function () {
my_jQuery("#myDiv").html("Hello world");
});
</script>
<div id="myDiv">
</div>
Of Course in real world logic will be more complex but principle is same.
So this must work even if site already have JQuery, if have same version of JQuery,if have different version of JQuery, or even if does not have JQuery at all.
I want be sure that client does not use some old version of JQuery, so I want always use my JQuery.
What do you think, will this work or there is something that I have not consider?
I think that this question should be faced in an architectural way, knowing what libraries/frameworks are available is a design concern... Basically, you shouldn't need to check dependencies at runtime... if you write jQuery, you must be sure that jQuery exists!
By the way, there are some cases where you can't do it, for example, if you are writing a public/api (a snippet that runs in heterogeneous environments). In these cases, you can do:
mark jQuery as peer-dependencies
Check at runtime.
There is an example of runtime checking:
<script>
(function($) {
var jQueryUrl = 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js';
$ || (document.writeln('<script src="'+ jQueryUrl +'"></script>'));
})(window.jQuery);
</script>
In order to avoid conflicts, finally, you don't need to use jQuery.noConflict, you need to work with javascript scopes (closures)... basically, never try to access the global jQuery alias $ (never use global vars), simple pass it as function param:
(function($) { console.log('$', $); })(window.jQuery)
window.jQuery(document).ready(function($) { console.log('$', $); });
The first thing we need to do is check if jQuery is present on the website. jQuery is the global variable so it should be in window object if it is loaded. We can check it like this: if (window.jQuery) {}
If the jQuery not present we can dynamically load it adding script tag with desired jQuery version. So the snippet answering for checking if jQuery is loaded and loading if it's not would be like:
if (!window.jQuery) {
var jq = document.createElement('script');
jq.type = 'text/javascript';
jq.src = 'http://code.jquery.com/jquery-1.12.1.min.js';
document.getElementsByTagName('head')[0].appendChild(jq);
}
That would work for
So this must work even if site already have JQuery,
if have same version of JQuery,
if have different version of JQuery,
or even if does not have JQuery at all.
As you can see as per your code, that would work fine for all three situations but 4th one. For this case you have to have a check to find if window has jQuery object. That can be done with:
if(window.jQuery){
var my_jQuery = $.noConflict(true);
my_jQuery(document).ready(function () {
my_jQuery("#myDiv").html("Hello world");
});
}
Note:
<script type="text/jscript">
would not work in the browsers other than IE.

"TypeError: $ is not a function" after loading some scripts into wordpress

We start to provide a HTML-Snippet like Google or Facebook does for its advertising things or the integration for the Facebook like button. It contains a business application.
Our HTML-Snippet loads a script and contains a few more informations:
<div id="ncc" data-hash="" ng-jq>
<div id="wiz" ng-controller="WizardCtrl"></div>
<script src="{{URLTOSCRIPT}}/load.js"></script>
</div>
The script checks if a jQuery is installed and loads all related things into the DOM and at the ends inits an angular-Application.
All this works fine on pages that havn't enabled jQuery.noConflicts-Mode.
After the latest Wordpress-Updates we got an ERROR
"TypeError: $ is not a function"
We tried to get rid of it using some workaroungs like
jQuery(document).ready(function($){
$(function () {
//code to execute
});
OR
jQuery(document).ready(function(){
var j = jQuery.noConflicts();
j(function () {
//code to execute
});
and changed also all references in the angular-part. But nothing working really well.
Any suggestions?
We are using AngularJs v1.4.7, jQuery v1.11.3 (started to migrate to 2.1.4), the
Sometimes when more versions of jQuery are loaded or if it conflicts with another library you can get that error:
have you tried to replace in all of your code the $ symbol with the word "jQuery"?
So your example would become:
jQuery(document).ready(function(){
jQuery(function () {
//code to execute
});
Note: I don't think that in this case passing "$" as a parameter is needed anymore ;)
EDIT: there is also another possibility:
you say that you're using the $ sign (i guess to avoid the usual conflicts in wordpress) in this way:
jQuery(document).ready(function($){
$(function () {
//code to execute
});
But this will make the $ symbol available only inside the ready() function.
Did you check if you have somewhere code using the $ where you actually aren't allowed to (or in other words if you have any piece of your js code where $ isn't mapped as "jQuery")?
EDIT 2: The only working solution in the end was:
(function($,undefined){
$(document).ready(function(){
//code to execute
});
})(jQuery);"
Make sure jQuery is loaded before any other script that uses certain jQuery functions.
Normally those errors arise, when the jQuery library wasn't loaded yet. Make sure that a $()-call is called after jquery was loaded, which normally happens at the end of your file to speed up loading times.
Therefore putting
<script src="{{URLTOSCRIPT}}/load.js"></script>
to the end of the body-tag should help.
Usually when you get this error: "TypeError: $ is not a function"
it means, you a missing a JQuery library or they are not placed in the correct order. Ordering JQuery libraries is important.
$ is not a function. It means that there is a function named $, but it does not have a plugin/widget named selectable. So, something has stolen your $ or there is another library added after it, or it was never loaded.
Your script file is not loading properly or script file is not available.
open browser inspect element and put this code
jQuery().jquery.
it's display which jquery version is use.
this is for testing
jQuery(document).ready(function()
{
alert("test");
});

How to properly use jQuery noConflict mode in Wordpress

I have the following functional (in html) jsfiddle:
http://jsfiddle.net/pmpvLjuq/1/
I've found that in order to be functional in Wordpress too, should be used in jQuery's noConflict mode. In wp codex I've found this section:
At this point, I'm not so sure if I understand the global term in these circumstances. Should I replace all the $ signs with jQuery ?
What I've done without error in the console (but I'm concerned) also working in wp pages it's here: http://jsfiddle.net/8r9rcft2/2/
In other words, in these particular cases should I still replace the $ mark(?)
line 15
$links = $(".pagedMenu li"), will be jQuerylinks = jQuery(".pagedMenu li"),(?)
line 16
count = $links.length, will be count = jQuerylinks.length, (?)
line
The same for lines 25,26,26, ect.
Can I have your prepared for wordpress jsfiddle in jQuery's noConflict mode in order to have the whole picture of this process please?
Can you please confirm, as a rule of thumb, if I dont receive any error in the browser console that means everything is fine in the code? Thanks
I always used jQuery like this in wordpress and it's working for me I hop this is working for you.
(function($){
$(document).ready(function(){
// write code here
});
// or also you can write jquery code like this
jQuery(document).ready(function(){
// write code here
});
})(jQuery);
I always prefer below method because it always separate jquery libraries and never conflict and it is one of recommended method of jquery.
Its just a example. I mostly used it for smooth scrooling.
$scroll= jQuery.noConflict();
$scroll('a').click(function(){
$scroll('html, body').animate({
scrollTop: $scroll( $scroll(this).attr('href') ).offset().top
}, 1000);
return false;
});

conflict between two jquery plugins with same function name

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.

JQuery - Test for a css class element exists. .length doesn't work

I need to check for an element with a css class being in existance on my HTML. I've Googled and searched here, and the common answer is to use .length > 0.
But that doesn't work. I'm getting an "Object expected" error. Any help greatly appreciated.
<script type="text/javascript">
if ($(".deleteLink").length != 0)
{
$(".deleteLink").click(function () { return confirm('some message?'); });
}
</script>
.deleteLink is a css class that belongs to a tag that may or may not be present. I'm getting the error on the conditional part.
Am I missing somethign?? Because it seems that everyone says to use .length...
Checking length is the correct way. There's something else wrong with your code. Did you perhaps forget to include jQuery? Is something clobbering $? Run it in something better than IE to get a more meaningful error message.
Also, a few tips. if ($(...).length) is enough because 0 is falsy, no need for the comparison. Also, you don't need to check if elements exist before manipulating them with jQuery (if it's something lightweight such as just attaching an event handler). Manipulating an empty jQuery result doesn't do anything.
Why this code is ok?
Your script should not throw an error if jQuery is loaded and $ is an alias for it (which is the default).
Also you can simply write:
$(".deleteLink").click(function(){ return confirm('some message?'); });
because the event handler will not be assigned to any element, if the selector does not find any.
Possible problems & solutions
The problem you are facing is one of the following:
the jQuery is not loaded, or
$ is not alias of jQuery.
To solve the first, just load jQuery before this part of the code. To solve the second you can simply use jQuery instead of $.
How to improve the code
One additional possibility is that the element is not available when the code is being executed. If you do not load it dynamically, you can just execute the code when the DOM is ready:
jQuery(function(){
jQuery(".deleteLink").click(function(){ return confirm('some message?'); });
});
This is a summation of the answers you already received.
The tags in your header should look something like this:
<head>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
<script>
$(function() {
$(".deleteLink").click(function () { return confirm('some message?'); });
});
</script>
</head>
load the jquery library before you use it
$(function() {}); just guarantees that the script is only ran when your document is ready (the elements are loaded
there is no need for that 'if' statement, if no elements are found, the click event will just attach to no elements.

Categories