Why is the $ alias not working for this jQuery function - javascript

jQuery(document).ready(function($) {
$('#customdivid').prepend($('<div class="myclass"></div>'));
})(jQuery);
I'm using Wordpress, and I understand that it runs in no conflict mode, but I thought if I wrote a function out as above I would be able to use $ instead of jQuery.
Script runs fine when I just use jQuery, but I want to understand what I'm doing wrong.
Thanks
Update: I guess what I'm really asking is how can I create this in a js file. jQuery = $
Would I just do var $ = jQuery
I read somewhere that I can include $ in the () after function and end the function with jQuery and all would be fine, hence my example above.
Hope I'm making sense
Thanks again!

You're confusing two different things. An IIFE (Immediately Invoked Function Expression):
(function($){
// $ is jQuery
}(jQuery));
With a ready event:
jQuery(document).ready(function($){
// now you can use $
});
If you simply pass a function to jQuery it's the same as the ready event:
jQuery(function($){
// use $
});

Related

jQuery $ not defined - Issues using window load

I'm getting a $ not defined error in the second case below, but not the first. jQuery is installed and working on the site.
Any code using $ in here runs fine:
jQuery(function($) {
alert("Yay!");
});
Anything inside of this errors with $ not a function:
jQuery(window).load(function($) {
alert("Why not!");
});
The error is because the load() event handler does not accept a jQuery object as an argument as document.ready (which is what your first example is shorthand for) does. In the second example your $ variable is actually a reference to the Event object, as such you're probably calling methods which don't exist.
If you want to use $ to reference jQuery, then it should be available by default. If for whatever reason it isn't, for example if you're using Wordpress, then you can use jQuery.noConflict() or an IIFE to re-alias it.
It's also worth noting that load() is deprecated. To hook to the window.load event use on():
jQuery(window).on('load', function() {
// your logic here...
});

Using $ instead of jQuery gives error

I'm using following jQuery code:
jQuery(document).ready(function() {
jQuery('#main').click(function(){
jQuery('#box').slideDown();
});
});
The above code works fine, however if I use $ instead of the jQuery, I get following error:
TypeError: $ is not a function
I understand that it is because of some conflict, but is there a way that I use $ in above code?
I have tried to use jQuery.noConflict(); also but it still gives same error.
Use this:-
jQuery(function($) {
$('#main').click(function(){
$('#box').slideDown();
});
});
Aliasing the jQuery Namespace
When using another JavaScript library, we may wish to call $.noConflict() to avoid namespace difficulties. When this function is called, the $ shortcut is no longer available, forcing us to write jQuery each time we would normally write $. However, the handler passed to the .ready() method can take an argument, which is passed the global jQuery object. This means we can rename the object within the context of our .ready() handler without affecting other code.
Reference
Try it like this,
$.noConflict();
jQuery(document).ready(function($) {
$('#main').click(function(){
$('#box').slideDown();
});
});
You could wrap it in a closure:
(function($){
// use $ as jQuery
})(jQuery);
You could use a closure:
(function ($) {
$(document).ready(function () {
$('#main').click(function () {
$('#box').slideDown();
});
});
})(jQuery)
First use noConflict.
var j = jQuery.noConflict();
then use
j(document).ready(function() {
j('#main').click(function(){
j('#box').slideDown();
});
});

Pass Jquery alias into javascript function

Im creating a theme for wordpress and I need to use some jQuery. Ive found bits of code online and ive made a few bits myself. However, when using jQuery provided by wordpress it is in noConflict mode and instead of using $ it is set to "jQuery". That is fine but I dont want to have to modify all my code and any code I find online to use "jQuery" instead of $.
So it tells me that by placeing function ($) at the end you are able to use the $ as the jQuery alias, but only in that functions scope. That is fine, but I was hoping that it would work and pass through to the functions I call from inside that scope. That is where my problem is. How can I make the jQuery code that uses $ inside my "resizeandcenter" function work.
jQuery('.artworklist > li > a > img').load(function ($){
resizeitems('artworklist');
});
This is my function that I want to be able to use the $ inside as I dont want to have to modify all my code / and any code I find online.
function resizeitems(elementname){
//Do some jquery stuff using $
}
Perhaps there is an alternative way to do what I am doing or I am doing it wrong?
EDIT:
My function "resizeitems" is on its own in a js file thats included in my page header.
The other code, the jQuery code in my first code block is at the bottom of the page in a script block.
So im a bit unsure about the answer saying to wrap my function?
You can wrap your entire code in a self executing closure (or an on ready/load closure) like this
(function ($) {
// do your stuff here
}(jQuery));
Then you can use $ within that closure
Here is an example on jsfiddle for you
window.addEventListener("load", function () {
(function ($jq) {
$jq("body").append($jq("<div>").text("hello"));
}(jQuery));
}, false);
Here is an example using jquery's ready event listener
jQuery(document).ready(function() {
(function ($jq) {
$jq("body").append($jq("<div>").text("hello"));
}(jQuery));
});
On jsfiddle
Or a further alternative in jquery, mostly syntax change, as suggested by #Mathletics
jQuery(function($jq) {
$jq("body").append($jq("<div>").text("hello"));
});
On jsfiddle
You need to pass jQuery into the top-level closure containing your code. Usually this is inside the $(document).ready() call. A basic example looks like this:
jQuery(function($) {
function resizeitems(elementname){
//Do some jquery stuff using $
}
$('.artworklist > li > a > img').load(function (){
resizeitems('artworklist');
});
});
jQuery is now aliased to $ inside of that closure.
All what matter is scope here. If your other functions are in some other scope you can just remap global jQuery to $ in that scope, so that you don't have to change the code.
var $ = jQuery;
You can even set it in global scope, but you may affect other usage of $ on the page if it was used for something else:
window.$ = jQuery;

Is this a double document ready?

I'm working with a script and have found the following, which I really can't find any info of what it means
(function($) {
$(document).ready(function(e) {
... bla bla bla ...
});
}) (jQuery);
Is (function($){}) (jQuery); the same as $(function () {}); ? and if so, why would somebody define twice document.ready ?
No, it's not the same. It's an anonymous function which is being passed the jQuery object, to insure that it is available as the local variable $ within the scope of the function, even if the global variable $ is overwritten by another library. It is completely different than $(function () { }) and $(document).ready(function () { }).
This particular pattern is recommended in the jQuery plugin authoring documentation:
[When authoring a plugin] it's a best practice to pass jQuery to an IIFE (Immediately Invoked Function Expression) that maps it to the dollar sign so it can't be overwritten by another library in the scope of its execution.
(function( $ ) {
$.fn.myPlugin = function() {
// Do your awesome plugin stuff here
};
})( jQuery );
Is (function($){}) (jQuery); the same as $(function () {}); ?
No. The first is immediate invocation of an anonymous function, used primarily for preventing pollution of the global scope. In this case, it's also used to make sure that $ is a reference to jQuery, without worrying about overwriting $ elsewhere.
The second is the shorthand for binding a document ready handler with jQuery.
More reading:
What is the purpose of a self executing function in javascript?
What is the reason for this JavaScript immediate invocation pattern?
No it isn't, (function($){}) (jQuery); is an IIFE(Immediately invoked function expression) passing jQuery as a parameter and using $ to represent it in the function scope so that no conflicts will occur if another library that uses $ is loaded without using jQuery.noConflict.
Nope
(function(){})();
is executed as soon as the browser encounters that script.
.ready() is an event that is triggered after the entire document is parsed
No it's not. It is a closure with a document ready handler inside it. It is used to ensure that the $ within the enclosure is reserved for jQuery and does not interfere with any other library.
A nice clear explanation here;
http://jquery-howto.blogspot.com/2008/12/what-heck-is-function-jquery.html

Window load wrapper for jQuery

jQuery(document).ready(function($){}); is a known and great way to protect the $ from causing errors.
What I'm curious about is if jQuery(window).load(function($){}); would work in the same way?
Basically, what I have now is:
jQuery(document).ready(function($){
$(window).load(function(){
// ...
});
});
This just seems unnecessary to me, any ideas about simplifying this? I need the safety of having jQuery properly mapped to $ (or whatever the correct term is) but the same timing as window.load()
I prefer this...
(function($){
$(window).load(function(){
//everything is loaded (images, scripts, etc.)
});
// and/or
$(document).ready(function(){
// the dom is in place, but everything is not necessarily loaded
});
})(jQuery);
Note: This will only work if jQuery was included before this script. I have never encountered any problems with jQuery being undefined this way. Furthermore, you will never have problems with $ being undefined, because you are passing it into your anonymous function.
You can do this:
(function($) {
$(window).load(function(){
// ...
});
})(jQuery);
The anonymous function will be executed immediately rather than waiting for DOM ready as in the code in the question. Within the function $ will be a reference to jQuery so won't clash with any other $ defined outside the anonymous function.
You can create a local parameter:
(function($) {
$(...)
})(jQuery);
This code executes an anonymous function with a parameter named $, passing jQuery as the parameter value.

Categories

Resources