I have a quick, beginners-type-question. If I were to use jQuery and some other framework, would the following statement be problematic:
jQuery(document).rea
jQuery(document).ready(function ($) {
$("input[name='password']").focus(function () {
$("input[value='login']").attr("checked", "checked");
});
});
Callback for ready() receives jQuery as an argument: you can call this argument $. This will override other $ definition in the scope of the callback.
When using multiple libraries that make use of $
, the common practice is to use noConflict mode and reassign the $
for jQuery to something else.
var $jq = jQuery.noConflict();
$jq( function() {
$jq("input[name='password']").focus( function() {
$jq("input[value='login']").attr("checked","checked");
});
});
In plugin development, a common way to handle this is to pass `$' in as a parameter to a function defining your plugin definition and applying the function to the jQuery object.
;(function($) {
...
})(jQuery);
You can wrap you jQuery code part into function like this:
function($) {
// jQuery code here
}(jQuery);
// use $ here to access other JS library
and you will be able to use $ inside the function (this is self-executing function that maps $ to jQuery.
For sure, make your code as explicit as possible - especially in this case. If the site changes later, you may end up calling the wrong library.
Yes, if you're using another library that uses $, you could use the full form jQuery or set up jQuery in no-conflict mode. E.g.:
<script>
jQuery.noConflict();
// Use jQuery via jQuery(...)
jQuery(document).ready(function(){
jQuery("div").hide();
});
// Use Prototype with $(...), etc.
$('someid').hide();
</script>
Another way to benefit from a short name while preventing conflicts with other libraries would be to do somthing like this:
<script>
var $j = jQuery.noConflict();
// Use jQuery via $j(...)
$j(document).ready(function(){
$j("div").hide();
});
// Use Prototype with $(...), etc.
$('someid').hide();
</script>
I would suggest reading this:
http://docs.jquery.com/Using_jQuery_with_Other_Libraries
What you've shown is correct except that you will want to replace all instances of '$'. You will then be overriding the '$' function.
jQuery(document).ready(function () {
jQuery("input[name='password']").focus(function () {
jQuery("input[value='login']").attr("checked", "checked");
});
});