close
Skip to content

Pass in jQuery's $ as a reference#2

Open
kingkool68 wants to merge 1 commit intojessabean:masterfrom
kingkool68:patch-2
Open

Pass in jQuery's $ as a reference#2
kingkool68 wants to merge 1 commit intojessabean:masterfrom
kingkool68:patch-2

Conversation

@kingkool68
Copy link
Copy Markdown

Most of the time this is fine $( document ).ready(function() { but sometimes jQuery is loaded in noConflict mode which means the shorthand $ is not mapped to the jQuery object. We can get the best of both worlds to maximize compatibility and convenience.

jQuery(document) will always work for selecting the document so long as jQuery is already included before this script is executed. We can pass a $ as an argument to the anonymous function that is being called when ready() fires. Thus everything within the function can use the shorthand $ instead of typing out jQuery everywhere.

You can also move all of the functions like convertToHex() and rgbToHex() inside of the jQuery( document ).ready(function($) { they will still work and better yet will be protected from function name collisions in the global scope. In other words, there could be another function named convertToHex used on the page and there won't be an error because one will be global and yours will be within its own scope. The downside to this is you can't call it outside of the context of your anonymous function which in reality means you can't open up dev tools, go to the console and type rgbToHex() and expect it to work.

Most of the time this is fine `$( document ).ready(function() {` but sometimes jQuery is loaded in noConflict mode which means the shorthand `$` is not mapped to the jQuery object. We can get the best of both worlds to maximize compatibility and convenience. 

`jQuery(document)` will always work for selecting the document so long as jQuery is already included before this script is executed. We can pass a `$` as an argument to the anonymous function that is being called when `ready()` fires. Thus everything within the function can use the shorthand `$` instead of typing out `jQuery` everywhere. 

You can also move all of the functions like `convertToHex()` and `rgbToHex()` inside of the `jQuery( document ).ready(function($) {` they will still work and better yet will be protected from function name collisions in the global scope. In other words, there could be another function named `convertToHex` used on the page and there won't be an error because one will be global and yours will be within its own scope. The downside to this is you can't call it outside of the context of your anonymous function which in reality means you can't open up dev tools, go to the console and type `rgbToHex()` and expect it to work.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant