How to make custom, no editing need, bulletproof jquery's noconflict version? - javascript

in my job i always have to use jquery with prototype can i make any custom jquery with library file like once i will add in head and then no need to change anything in any code.
is it possible?
I don't want to change anything in an code $ to jQuery.

from http://www.cssnewbie.com/runing-jquery-with-other-frameworks-via-noconflict/
Keeping it Short
The noConflict mode does have one other bit of functionality that I’ve found useful in some of my projects: you can select a different variable to use instead of the standard “jQuery”. The usage looks like this:
var $j = jQuery.noConflict();
Now in addition to using the default jQuery() notation, I can also use the shorter $j() notation. This allows me to avoid running into problems with other frameworks, while still enjoying almost the same conciseness in my code.

This just begs the question why dont you simply implement all your stuff in Prototype then - or implement everything in jQuery. Overall they both have the same capabilities.
However to directly answer your question - ther isnt really a way to make a custom build of jQuery. But you could simply put your noConflict call immediately following your inclusion of the jQuery library.
Then for your stuff you can simply wrap it all in
(function($){
// your jQuery code here... Can be used with $ as normal.
})(jQuery);
within that function youll be able to use $ as the alias - outside of it you would need to use jQuery. The only gotcha here is that if you want a variable defined inside here to be global youll need to make it that way manually as everything within this will be scoped to the function. You can do this like so:
(function($){
window.myGlobalVar = 'This is a global variable';
})(jQuery);

The best thing is often to wrap the $ in a private scope:
(function($) {
// jQuery stuff
})(jQuery)
You can also call the jQuery.noConflict() function before the wrap: http://api.jquery.com/jQuery.noConflict/
Another clean option is chaining the noConflict() into a domReady callback:
jQuery.noConflict()(function($){
// code using jQuery or $
});
console.log(typeof $ === 'undefined') // prints true

To address your question of whether you can have an "include-once" file, yes, you could do something similar to:
/* MyLibLoader.js */
document.write("<script type='text/javascript' src='prototype.js'></script>");
document.write("<script type='text/javascript' src='jquery.js'></script>");
window.$j = jQuery.noConflict();
And then in HTML
<head>
<script type='text/javascript' src='MyLibLoader.js'></script>
</head>
But this approach assumes you're happy to change your jQuery usage to $j

Related

Adjusting jQuery to work on Wordpress (syntaxerror)

I have a line of code that has a "$" value in it, which Wordpress doesn't seem to accept. How to adjust the "$", so that Wordpress will read it correctly?
jQuery(document).bind('gform_post_render',function(){
jQuery('#input_24_4').change(function(){
jQuery('#input_24_3').data('amount',$(this).val());
});
});
$ should be an alias of jQuery, anyway, for some reason $ is not defined sometimes. You can fix it by using an anonymous function:
(function($) {
$(document).bind('gform_post_render',function() {
$('#input_24_4').change(function(){
$('#input_24_3').data('amount',$(this).val());
});
});
})(jQuery);
Also, make sure you've loaded jQuery library before embedding / executing this piece of code.
Where is this line of code? If it's part of a double-quoted string in any of your PHP files, you need to escape the $ with a backslash: \$
Apart from that, jQuery runs in noConflict mode in Wordpress. That means, it doesn't set the global $ variable, just the jQuery name.
If you want to change that, you need to set it yourself somewhere before this line:
window.$ = window.jQuery;

What does the command that start with '$.' do/mean in Javascript? This is NOT '$' selector to select an element [duplicate]

In the following JavaScript code there is a dollar ($) sign. What does it mean?
$(window).bind('load', function() {
$('img.protect').protectImage();
});
Your snippet of code looks like it's referencing methods from one of the popular JavaScript libraries (jQuery, ProtoType, mooTools, and so on).
There's nothing mysterious about the use of $ in JavaScript. $ is simply a valid JavaScript identifier. JavaScript allows upper- and lower-case letters (in a wide variety of scripts, not just English), numbers (but not at the first character), $, _, and others.¹
Prototype, jQuery, and most javascript libraries use the $ as the primary base object (or function). Most of them also have a way to relinquish the $ so that it can be used with another library that uses it. In that case you use jQuery instead of $. In fact, $ is just a shortcut for jQuery.
¹ For the first character of an identifier, JavaScript allows "...any Unicode code point with the Unicode property “ID_Start”..." plus $ and _; details in the specification. For subsequent characters in an identifier, it allows anything with ID_Continue (which includes _) and $ (and a couple of control characters for historical compatibility).
From another answer:
A little history
Remember, there is nothing inherently special about $. It is a variable name just like any other. In earlier days, people used to write code using document.getElementById. Because JavaScript is case-sensitive, it was normal to make a mistake while writing document.getElementById. Should I capital 'b' of 'by'? Should I capital 'i' of Id? You get the drift. Because functions are first-class citizens in JavaScript, you can always do this:
var $ = document.getElementById; //freedom from document.getElementById!
When Prototype library arrived, they named their function, which gets the DOM elements, as '$'. Almost all the JavaScript libraries copied this idea. Prototype also introduced a $$ function to select elements using CSS selector.
jQuery also adapted $ function but expanded to make it accept all kinds of 'selectors' to get the elements you want. Now, if you are already using Prototype in your project and wanted to include jQuery, you will be in problem as '$' could either refer to Prototype's implementation OR jQuery's implementation. That's why jQuery has the option of noConflict so that you can include jQuery in your project which uses Prototype and slowly migrate your code. I think this was a brilliant move on John's part! :)
That is most likely jQuery code (more precisely, JavaScript using the jQuery library).
The $ represents the jQuery Function, and is actually a shorthand alias for jQuery. (Unlike in most languages, the $ symbol is not reserved, and may be used as a variable name.) It is typically used as a selector (i.e. a function that returns a set of elements found in the DOM).
As all the other answers say; it can be almost anything but is usually "JQuery".
However, in ES6 it is a string interpolation operator in a template "literal" eg.
var s = "new" ; // you can put whatever you think appropriate here.
var s2 = `There are so many ${s} ideas these days !!` ; //back-ticks not quotes
console.log(s2) ;
result:
There are so many new ideas these days !!
The $() is the shorthand version of jQuery() used in the jQuery Library.
In addition to the above answers, $ has no special meaning in javascript,it is free to be used in object naming. In jQuery, it is simply used as an alias for the jQuery object and jQuery() function.
However, you may encounter situations where you want to use it in conjunction with another JS library that also uses $, which would result a naming conflict. There is a method in JQuery just for this reason, jQuery.noConflict().
Here is a sample from jQuery doc's:
<script src="other_lib.js"></script>
<script src="jquery.js"></script>
<script>
$.noConflict();
// Code that uses other library's $ can follow here.
</script>
Alternatively, you can also use a like this
(function ($) {
// Code in which we know exactly what the meaning of $ is
} (jQuery));
Ref:https://api.jquery.com/jquery.noconflict/
From the jQuery documentation describing the jQuery Core Object:
Many developers prefix a $ to the name of variables that contain jQuery
objects in order to help differentiate. There is nothing magic about
this practice – it just helps some people keep track of what different
variables contain.
Basic syntax is: $(selector).action()
A dollar sign to define jQuery A (selector) to "query (or find)" HTML elements A jQuery action() to be performed on the element(s)

simple jquery widget

jQuery.widget("ui.test", {
_init: function(){
alert(this.element.innerHTML);
}
});
How do I make it so when I am attaching this to a HTML element
It will alert the innerHTML (I know it does nothing, it is just to understand the basics).
<div id="baba">ja jaj</div>
<script>
$('#baba').test();//will alert "ja jaj"
</script>
What am I missing here?
What I missed:
My code was actually perfectly fine, EXCEPT, I assumed that this.element is an HTML element, while in reality it is a jQuery object. Hence innerHTML did nothing while html(), in the answer below, worked.
You're missing the jQuery UI library. Simply attach it and yu're good to go - http://jsfiddle.net/jUm5H/
(function($) {
$.widget("ui.test", {
_init: function() {
alert( this.element.html() );
}
});
}(jQuery));
$('#baba').test();
UPDATE
"To make sure that your plugin doesn't collide with other libraries that might use the dollar sign, 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." - source
So it's basically just a good practice. You can ignore it and it will work - http://jsfiddle.net/jUm5H/1/ But it's better to do it in a correct way from the beginning. It might save a lot of debugging time and frustration in the future projects :)

$ vs. jQuery: Which should I use?

What is the diffrence between them? Which is better?
$ is an alias for jQuery, neither is "better" really, jQuery is provided in case something else is using $, like Prototype (or jQuery.noConflict() was called for another reason...).
I prefer $ for brevity because I know it refers to jQuery, if you're unsure (like when writing a plugin) use jQuery for your primary reference, for example:
(function($) {
//inside here $ means jQuery
})(jQuery);
The functionality is identical if there is no conflict.
Use 'jQuery' instead of '$' to be especially explicit/descriptive, or if you currently use or anticipate using another library that defines '$'.
See also http://api.jquery.com/jQuery.noConflict/
jQuery == $ == window.jQuery == window.$
jQuery and $ are defined in window, and $ can be used if no other library is making use of it, thus creating conflicts.
Either use jQuery.noConflict() or closures:
(function ($) {
// code with $ here
})(jQuery)

Unify $ function of Prototype and JQuery

Is there any JavaScript function that can unify $ function from both Prototype and jQuery?
Yes, this is the real use case I am facing now. I find $ function in Prototype and $ in jQuery is conflicting each other. I know that we could us jQuery.noConflict() to ressign $ back to Prototype, however by doing so, I will have to rewrite jquery-specific javacript code that use that $ function, or have jquery specific in a code block (eg. anonymous function).
Is there any easier way, without having to rewrite existing code in both library and have them in one page?
The code that could answer this question may look like this, and your feedback is greatly appreciated:
<script type="text/javascript" src="/path/to/prototype.js"></script>
<script type="text/javascript" src="/path/to/jquery.js"></script>
<script type="text/javascript">
/* <![CDATA[ */
var $j = jQuery.noConflict();
var $p = $; // reference to prototype's $
var $ = function(E, F){
var isJQuery = true;
//TODO: logic to determine which $ to use here YOUR SUGGESTION HERE ;-)
var result = null;
if(isJQuery){
result = $j(E, F);
} else { // prototype
//TODO: code to delegate prototype $
}
return result;
}
/* ]]>*/
</script>
// ... any existing javacode jQuery and Prototype using $ function.
Thanks.
update: Rewrite question to be more clear.
Well, first of all, I can rarely find usefull cases where both of the libraries have to be included in the same page. So you might consider to remove one.
I guess that this is due to a plug-in use, but have a look at the opponent plug-in list, I'm quite sure that there is an alternative.
Second, for your jQuery specific code, it's quite easy to rewrite it, using the anonymous function trick:
(function($){
... your code here ...
})(jQuery);
This will work in most of the cases where you don't put global variables or methods rather than binding them to events.
I've always got into the habit of putting all my jQuery code into a function, similar to gizmo's example:
jQuery(function($) {
// jQuery code here, using $
});
this is the same as the document.ready event handler.
jQuery's been great about making sure they play well with Prototype. Check this page for details, Avoiding Conflicts with Other Libraries.
I've seen both libraries used in the same pages before and it is generally because of third-party apps that are in your pages that use one library while your pages use the other. However, if you're doing all the development yourself, I suggest sticking with one or the other.

Categories