So I had code that was working properly on my site:
$("#usr").load("somepage.php",{var1:var1,var2:var2});
But ever since I changed some code in the navigation bar, jQuery has been acting really strangely. The first major problem was that this line:
var w = $(window).width();
returns the error: object [global] has no method "width()"
And that didn't seem to matter, as all elements on the page functioned with that error (as if it was still being executed, because elements were still being placed)...but then I came to the page that implemented the first line of code, and I ran into the following error:
Cannot call method "load()" of null
Sure enough, I checked the console, and $("#usr") returns null, but I can see the HTML line in the page with the inline id of usr.
This causes a problem because I need to load data from that page for the page to function properly. But it gets even stranger. I thought I would just try a plain post request and take the data and use document.getElementById("usr").innerHTML = ... as a substitute, but I get the following error from this line:
$.post("somepage.php",{var1:var1,var2:var2},function(data){
document.getElementById("usr").innerHTML = data;
});
Error:
Uncaught TypeError: Object function $(el){if(!el)return null;if(el.htmlElement)return Garbage.collect(el);if([window,document].contains(el))return el;var type=$type(el);if(type=='string'){el=document.getElementById(el);type=(el)?'element':false}if(type!='element')return null;if(el.htmlElement)return Garbage.collect(el);if(['object','embed'].contains(el.tagName.toLowerCase()))return el;$extend(el,Element.prototype);el.htmlElement=function(){};return Garbage.collect(el)} has no method 'post'
What the heck is going on with jQuery?
I'm importing 1.8.2 from googleapis
That sounds a lot like you're loading Prototype or MooTools or something as well as jQuery, and so Prototype/MooTools/whatever is taking over the $ symbol.
If that's what's going on, and you need the other library, you can use jQuery.noConflict(). Then you either use the symbol jQuery instead of $ for your jQuery stuff, or you put all of your jQuery code into a function that you pass into jQuery.noConflict and accept $ as an argument, like so:
// Out here, $ !== jQuery
jQuery.noConflict(function($) {
// In here, $ === jQuery
});
Or you can just do it yourself:
// Out here, $ !== jQuery
jQuery.noConflict();
(function($) {
// In here, $ === jQuery
})(jQuery);
ready also passes the jQuery object into the function, if you're already using ready.
Related
I have a page that I am trying to remove an element of with this section of code
oldContainer = $('div.choose-location-options');
oldContainer.addClass('hidden');
I am using the $ selector because I read online and in this answer that $ is short for document.querySelector, this code is working fine.
During code review my colleagues have told me that they do not want us using the $ is not best practice because it looks like jquery. So I changed it to this.
oldContainer = document.querySelector('div.choose-location-options');
oldContainer.addClass('hidden');
However this code will return an error message saying that cannot add class to undefined
Running this code in the browser will also remove the oldContainer so I thought it was an issue with the page loading so I added an event listener to the code for a page load
window.addEventListener('load', (event) => {
oldContainer = $('div.choose-location-options');
oldContainer.addClass('hidden');
});
This also returns undefined So I know it is not a timing issue. Why is the shorthand $ working but not the document.querySelector?
I'm learning the module pattern for javascript in order to tidy up my code and reduce the need for a long 'global' javascript file.
As a consequence of this, I have a top level 'namespace' module, and a utility module in the same file. The utility module has some functions that require jquery, and others that do not.
On lightweight pages that use no jQuery, I don't want to load the library (I have a very good reason for not doing so).
The problem arises when jQuery is passed as a parameter to the module as in the following:
MODULE.vars = (function (variables,$) {
variables.cdn = undefined; //global for clientside cdn
variables.version = undefined; //global for clientside cdn version
variables.isTouchScreen = undefined; //global for touchscreen status
//Check if jquery exists, if so patch the jquery dependent functions
if ($) {
$(document).ready(function () {
variables.isTouchScreen = $('html').is('.touch');
});
}
return variables;
}(MODULE.vars || {}, jQuery));
The code stops on pages that I don't load jquery, stating that jQuery is undefined - fair enough. If I change the last line to:
}(MODULE.vars || {}, jQuery || false));
the code still complains that jQuery is undefined. I thought, perhaps erroneously, that if jQuery was undefined, it would be passed as undefined in this instance and instead take up the value false (which logic dictates wouldn't be necessary anyway).
How do I get around this problem when jQuery may or may not be present? I attempted to put the following at the top of the script:
var jQuery = jQuery || false;
thinking that this would then take up the value of jQuery if it was loaded. It works in modern browsers with this, but IE8 complains as it gets set to false even if jQuery is being loaded first on a page.
The scripts are all loaded in the correct order in the html, jQuery first, then my module afterwards.
When checking for the cause, IE8 returns $ as an object and jQuery as false. If i do not set the above line in the script, jQuery returns as the same object as $.
Sadly I have to cater for IE8 as well, so how do I get around this issue of the optional presence of jQuery?
Edit: This is only a snippet of the module and there are other functions that depend on jquery, but simply won't get implemented if jquery is not available
I seem to have found an answer that works after I worked out how to implement elanclrs suggestion - I put the following at the top of my modules:
var jQ = jQ || false;
if (typeof jQuery !== 'undefined') {
jQ = jQuery;
}
Then in my module, I pass jQ instead of jQuery.
The reasoning behind the answer was pointed at in this question: Error when passing undefined variable to function?
Hey all looking throughout all of stackoverflow this looks like a common error i just cant wrap my head around. i am busy upgrading our site from pure JS to jquery in preparation for us moving over to Rails 3.1 now i have this javascript:
:javascript
["Ownership", "Management", "EmploymentEquity", "SkillsDevelopment", "PreferentialProcurement", "EnterpriseDevelopment", "SocioeconomicDevelopment"].each(function(element) {
$$('.' + element).each(function(s) {
s.toggle();
});
});
so basically it is running trough an array of css classes and then toggling them. now when i run this with the jQuery lib i get an error that looks like this
Uncaught TypeError: Object Ownership,Management,EmploymentEquity,SkillsDevelopment,PreferentialProcurement,EnterpriseDevelopment,SocioeconomicDevelopment has no method 'each'
now i am just trying to test one element at a time to get the jQuery working at least this is what i have so far.
$("OwnershipHeader").click(function () {
$("Ownership").toggle("slow");
});
very simple so just when you click on the header it toggles its children. so when i enter that in the console it works just fine. until i click on the header of coarse:
Uncaught ReferenceError: $$ is not defined
this seems really simple and yet its breaking every time... i am relatively new to jQuery i have just worked with the Jquery UI lib before. any suggestions are appreciated
Uncaught TypeError: Object Ownership,Management,EmploymentEquity,SkillsDevelopment,PreferentialProcurement,EnterpriseDevelopment,SocioeconomicDevelopment has no method 'each'
I think you meant forEach. But since this doesn't work in all browsers, use jQuery's each function
$.each(["Ownership", "Management"], function(i, element) {...
Uncaught ReferenceError: $$ is not defined
jQuery uses a single dollar sign ($)
$("OwnershipHeader").click(function () {
$("Ownership").toggle("slow");
});
jQuery selectors are mostly like CSS selectors. So this should work:
$(".OwnershipHeader").click(function () {
$(".Ownership").toggle("slow");
});
Try this.
var array = ["Ownership", "Management", "EmploymentEquity", "SkillsDevelopment", "PreferentialProcurement", "EnterpriseDevelopment", "SocioeconomicDevelopment"];
$.each(array, function(i,element) {
$('.' + element).toggle();
});
It looks like it was coded previously with PrototypeJS, which provides $$ and [].each.
I'm not sure if .toggle is the same behavior in PrototypeJS and jQuery.
var col = ["Ownership", "Management", "EmploymentEquity", "SkillsDevelopment", "PreferentialProcurement", "EnterpriseDevelopment", "SocioeconomicDevelopment"];
$.each(col,function(i,e){
$('.'+e).each(function(j,s){
$(s).toggle();
});
})
*in jquery first of all there is no variable defined as $$ and only $ is defined.
*secondly each function is used as i have mentioned and the first variable passed to the function that is provided to each is the index in array and second variable is the actual element
look here for each and toggle documentation
I need some scripts inside an existing site's scripts.js.
This site has been online for ages, and I can not touch the scripts file.
I am including it standardly in another page. There are numerous jQuery calls in the scripts file. The place I include it does not have jQuery.
I want to void all $() type things. I tried this...
$ = function() { };
before I included scripts.js and it didn't seem to work. I am still getting errors like
$(document) is undefined
Is there a way to void all these jQuery calls?
Thanks
Even if you do get that working, you'll still have problems because the code was written with the assumption that jQuery was present. Yes, you can avoid $ is null or not defined errors on lines like this:
$('div.foo');
But there's no point in just writing that line: there will always be actions on the returned object:
$('div.foo').html('blah');
After the NOP jQuery function, you'll get a "html" is not a function error, and so on. The only way you could do it would be to fill out a skeleton of every possible jQuery method, making sure each one returns itself when appropriate.
...or just rewrite it properly...
try
window.$ = function(selector, context) {alert('eating the calls to $');}
in your file that you're including before the scripts.js file. This is how it's defined in jquery so should take care of the selector syntax.
You may need to define other overrides to cater for the $.method() type calls tho
Well, it's no surprise that $(document) is undefined, since you're not returning a value from your placeholder function. Thus, things like $(document).ready(function(){}); will naturally be errors.
Basically, if I understand right, you need $ to be a function that does nothing and returns another object where calling any member function does nothing. Further, calling member functions of $ itself (e.g. $.ajax()) should have the same behavior.
You can do this with __noSuchMethod__, which is unfortunately non-standard:
window.$ = function()
{
var doNothingObj = new (function()
{
this.__noSuchMethod__ = function()
{
return doNothingObj;
}
})();
return doNothingObj;
};
window.$.__noSuchMethod__ = window.$;
This will allow arbitrary chains:
$(document).ready(function(){});
$("#foo").animate().animate();
$.ajax({ url: "file.html"});
etc.
Of course, a much saner solution is to refactor the code that uses jQuery.
I recently transferred a site to a new host. Reloaded everything, and the javascript that worked fine before is breaking at an element it can't find. $('#emailForm') is not defined.
Now, the #emailform isn't on the page, but it wasn't before either, and JS used to skip this and it would just work. Not sure why this is happening. Any clues
Here is the site I am having the prblem:
http://rosecomm.com/26/gearwrench/
jQuery will return an empty jQuery object from $('#emailForm') if there isn't an element with the id='emailForm'.
One of the following is likely true:
You forgot to include jQuery - therefore $ is undefined.
There is another library included that uses $ - in which case you can wrap your code in a quick closure to rename jQuery to $
The Closure:
(function($){
// $ is jQuery
$('#emailForm').whatever();
})(jQuery);
You could console.log(window.$,window.jQuery); in firebug to check for both of these problems.
You have mootools-1.2.2-core-yc.js installed as well, and it is conflicting with jQuery.
http://docs.jquery.com/Using_jQuery_with_Other_Libraries
$(document).ready(function() {
(function($){
// bind 'myForm' and provide a simple callback function
$('#emailForm').ajaxForm(function() {
var txt=document.getElementById("formReturn")
txt.innerHTML="<p>Thank You</p>";
});
...
$(document).ready is being called against the moo tools library instead of jQuery.
I'm not sure why it would be skipped before, but to avoid the error, wrap the statement(s) that reference $('#emailForm') in an if statement that checks to see if it is present:
if ( $('#emailForm').length ) {
// code to handle $('#emailForm') goes here...
}