I have a couple of interview questions
What is the different between $(function(){}); and $(document).ready(function(){});
What is the difference between $(function(){}); and var func=function(){}; How are each of them called?
Given the following script
<script language="javascript">
$(function()
{
var id=$("cssID");
//do something with your id
//your event to be added here
});
</script>
How can you add an event, say, onmouseout that will work on the id?
Here are my answers:
They are the same, both are meant to run when the page document finishes loading
The first one is called automatically while the second one will be called via named reference; that is func.called(), for example.
Something like this:
$(function()
{
var id=$("cssID");
//do something with your id
//Oki
id.onmouseout
(function(){
//do something
});
});
However my professor says I was wrong in all three. she explained things I am unsure and didn't dare to ask, she was mad about me. What are the correct answers and why are mine wrong?
These are the different types of Document Ready functions typically used in jQuery (aka jQuery DOM Ready). A lot of developers seem to use them without really knowing why. So I will try to explain why you might choose one version over another. Think of the document ready function as a self-executing function which fires after the page elements have loaded.
See Where to Declare Your jQuery Functions for more information on how to use the Document Ready Functions.
Document Ready Example 1
$(document).ready(function() {
//do jQuery stuff when DOM is ready
});
Document Ready Example 2
$(function(){
//jQuery code here
});
This is equivalent to example 1… they literally mean the same thing.
Document Ready Example 3
jQuery(document).ready(function($) {
//do jQuery stuff when DOM is ready
});
Document Ready Example 4
(function($) {
// code using $ as alias to jQuery
$(function() {
// more code using $ as alias to jQuery
});
})(jQuery);
// other code using $ as an alias to the other library
Document Ready Example 5
$(window).load(function(){
//initialize after images are loaded
});
Here is the link for you to refer.
1. They are the same, both are meant to run when the page document finishes loading
This is half right. They are the same, the first is just a shortcut way to write the second, but they don't run when the document finishes loading, they run when the DOM is ready (at which time some resources such as images might still be loading).
2. The first one is called automatically while the second one will be called via named reference; that is func.called(), for example.
Again half right. In the first one the anonymous function will be called automatically when the DOM is ready as per question 1. The second example can be called with func(). You wouldn't have the .called part in there. Or you can pass func as a parameter, e.g., as $(document).ready(func).
Q3
var id=$("cssID");
How can you add an event, say, onmouseout that will work on the id?
$("cssID") creates a jQuery object that will contain zero or more elements depending on how many matched the "cssID" selector. The id variable references that jQuery object. If the question is how to assign an event handler to those matching elements you'd do this:
id.mouseout(function() { /* some code */. });
// OR
id.on("mouseout", function() { /* some code */ });
When processing events with jQuery you don't use "on" in the event names, so it's "mouseout" not "onmouseout".
So your answer to 3 was nearly right.
(Note though that "cssID" is a selector that won't actually match any elements unless you have <cssID> tags in your document...)
There is no difference between:
$(functionValue);
And:
$(document).ready(functionValue);
So your professor is wrong there. The second example is completely different. One of them runs on document ready and requires jQuery; the other one is just a function literal assigned to a JavaScript variable.
As for the third one, you'd probably do it with on. onmouseover is correct if you use get, but not really the best way of going about things, and you definitely wouldn't call it like you're doing there - that's completely incorrect.
id.on('mouseout', yourHandler);
or
id.mouseout(yourHandler);
Related
I'm building a chrome extension and included the following code in my content script. pep is a library for making things draggable. Interestingly, my code worked for case #2 but not #1. Why is that so?
It seems like the second case is wrapping the function call with an anonymous function (although I'm not sure why the jquery is needed before that)
//1
$('#square').pep();
//2
$(function($) {
$('#square').pep();
});
The second case is jQuery's shorthand for "on document ready".
It's the equivalent of:
$(document).ready(function() {
$('#square').pep();
});
Documentation: https://api.jquery.com/ready/
In the second case you are using a shorthand for $(document).ready(). That way the javascript waits for all the DOM elements to load before executing. The library needs all element to be loaded in order to work.
https://learn.jquery.com/using-jquery-core/document-ready/
A function passed to jQuery constructor, $(function() {}), is a shorthand for $(document).ready(function() {});
The function argument doesn't have to be anonymous, in fact, it's a good practice to always name such functions like so $(function myDomReady() {}).
EDIT Helping people understand the question better
Can you call a argument and then use it in jQuery? I was thinking something like:
// Notice the "test" argument in the "foo" function
function foo(test) {
$("#randomDiv").click(function(){
$(test).toggle();
});
}
Would something like this work?
Yes, it will work. But it depends on what you want to achieve.
Your code will be something like a "instant-binder", eg: this code will bind toggling of the element when the document is parsed.
As far as you can bind many listeners for one event, following calls of the same functions will be executed in order.
You should run foo at the beginning of the html file. On that way you will be sure that the function document.ready would run wait until all the DOM is loaded.
I'm trying to do something deceptively simple -- adding a class to the active backbone element. The code I want to use is:
this.$el.addClass('classIWant');
However, this doesn't work all the time. Sometimes it seems to, but not all the time. However, this always works.
var id = this.$el.attr('id');
$('#' + id).addClass('classIWant');
Obviously I don't want the second example, as it relies so heavily on HTML and the DOM. Is there any reason why the first shouldn't work, or am I missing something else?
Seems this points to something wrong. If you are running this code in function myFunc, then just add to initialize next line:
_.bindAll(this, 'myFunc');
And got with you first approach, this.$el.addClass('classYouWant').
This code should work:
this.$el.addClass('classIWant');
but only if it is present within your onRender() function or any functions that are called after onRender() is. If you have this code in your initialize function then it will not work as the dom for that view has not yet been generated
I have following code that works -
$(function(){
$('#testbutton').click(function(){
var checkedValue = $('[name="someRadioGroup"]:radio:checked').val();
$('#result').html('The radio element with value <tt>' + checkedValue + '</tt> is checked');
});
});
I understand that $('#testbutton') fetches the HTML element with id testbutton and assigns an event handler to it.
But I don't understand why I need to put that code inside a function literal?
If I remove the $(function(){ (and the corresponding }); ) it does not work.
However other code can work without being wrapped in a function literal. Example -
alert('Hi there')
What is the difference? Why does alert work but the event assignment statement does not?
$(function(){...}); is shorthand for $(document).ready(function(){...});. The purpose of it is to not run your code until the elements that you intend to work with exist in the DOM (which generally is after the document is ready.)
It is not a requirement.
You are putting your code in an event handler that is invoked when the DOM is ready.
If you don't put your code in a DOM ready handler, and if your code performs DOM selection, you need to find some other way to to make sure the DOM is ready before it runs.
If your code doesn't perform DOM selection, then it's not needed. That's why your alert() works, because it doesn't need to fetch any elements.
An alternative is this.
<body>
<button id="testbutton">click</button>
<div id="result"></div>
<script type="text/javascript" src="/your/script.js"></script>
</body>
This places your code below all the elements on the page, so they are certain to be available when your code runs.
Another alternative is to use a window.onload handler.
window.onload = function() {
// your code
};
or using jQuery.
$(window).on("load", function() {
// your code
});
This is similar to the DOM ready handler, except that it waits for all resource, like images, to be loaded.
At the most basic level, something of the form (function(){...})() is a function literal that is executed immediately. What this means is that you have defined a function and you are calling it immediately.
This form is useful for information hiding and encapsulation since anything you define inside that function remains local to that function and inaccessible from the outside world (unless you specifically expose it - usually via a returned object literal).
A variation of this basic form is what you see in jQuery plugins (or in this module pattern in general). Since you are defining a function literal, it doesn't have access to anything from the outside world unless you explicitly pass in the information. Hence:
(function($) {
...
})(jQuery);
Which means you're passing in a reference to the actual jQuery object, but it's known as $ within the scope of the function literal.
Here is the code block a
$('ul.filter li').each(function() {
$(this).click(function(e) { //do something });
});
Here is code block b
$('ul.filter li').click(function(e) { //do something });
Don't these do the same thing? is one better than the other? Which one is the better/faster method?
I would assume block b since it has less code but I want to confirm it here, thanks
The effect you see will be the same, but in the first case, every li element is assigned a new function, as you are creating the function object inside the each callback.
In the second case, there exists only one copy of the event handler, which means it uses less memory over all (although this is probably not measurable).
Internally, click calls on (in jQuery 1.7), which is iterating over the elements via each as well:
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
This is the case with many jQuery methods (most often noted in the documentation), so you are saving characters and memory by letting jQuery implicitly do this.
They would both have the same effect.
I would prefer the second only because it is more concise and you're creating a single anonymous function to handle the click rather than an anonymous function per element.
For Jquery philosophy, the second is better because it is shorter.
Both are more or less same and give the same results. The second code snippet will also internally run each loop and assign the click handler to each li element.
But yes the second code snippet is very clear and simple.
The second usage is called "implicit iteration" and is one of the cornerstones of jQuery.
For example, in JavaScript Definitive Guide, 6th Ed, p.530 for jQuery Basics:
Despite the power of the each() method, it is not very commonly used,
since jQuery methods usually iterate implicitly over the set of
matched elements and operate on them all. You typically only need to
use each() if you need to manipulate the matched elements in
different ways. Even then, you may not need to call each(), since a
number of jQuery methods allow you to pass a callback function.
in http://jqfundamentals.com/chapter/jquery-basics
Implicit iteration means that jQuery automatically iterates over all
the elements in a selection when you call a setter method on that
selection. This means that, when you want to do something to all of
the elements in a selection, you don't have to call a setter method on
every item in your selection — you just call the method on the
selection itself, and jQuery iterates over the elements for you.
Typically, when the library has this built-in as the standard way of doing it, it will be in general better and faster, or else they wouldn't have built it in.