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() {}).
Related
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 am having trouble with this in Jquery. When I do that on my website, it returns me the window.width. I just want to access the element from within. This is an example.
<div class="section " style="width:400px"></div>
$( ".section" ).html($(this).width());
or
<div class="section "><p></p></div>
$( ".section p" ).html($(this).parent().width());
also here is JSFiddle jsfiddle.net/XY66w/1
I'm going to assume that when you attempt to write this code:
<div class="section " style="width:400px"></div>
$( ".section" ).html($(this).width());
What you're trying to do is show 400px inside the div.section. If that is what you're trying to do, then here's what's happening:
This statement:
$( ".section" ).html($(this).width());
if Javascript, or most other languages I know, is syntactically equivalent to this:
var newHTML = $(this).width();
$( ".section" ).html(newHTML);
As you can see, this isn't a jQuery issue - but more a JavaSciprt / any programming language problem. You're telling the browser to pass in a value to the .html() method, so it must calculate that value first, in the scope of the function that you're calling the method from. In this case, you're calling the method from the window or global scope (or some other undefined scope, so you will never get what you expect.
The simple fix is this:
var section = $('.section');
section.html(section.width());
On the other hand, there are some jQuery methods that accept functions and these are the ones that you seem to be thinking of in this case. For instance, things would be slightly different in case you were using the each method, which accepts a function:
$('.section').each(function(index, element){
$(this).html($(this).width());
});
In this case, you're passing in a function that jQuery will then call in the scope of each element that is matched by your selector.
The big difference is to differentiate when you're passing in a value and when you're passing in a function that will be evaluated later.
You can do what you want this way, I think:
$(".section").each(function() {
$(this).html($(this).width());
});
JavaScript, like a lot of common languages, is not a "lazy" language. An expression statement like yours is evaluated such that all the function parameters are determined before anything's actually called. By using the jQuery .each() API, you can act on each element of the selected set.
jQuery only binds this when it's calling a function, such as an event handler, a callback function, a function supplied to something like $.each, etc.
In your examples, you're just supplying an argument to a jQuery method, and it's not inside a function that was called by jQuery. So this just contains whatever the browser's context is, which is window for top-level code. It's not the element(s) matched by the selector .section.
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);
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.
I dont understand javascript syntax well,my question:
How jquery define click function for get parameter inside anonymous function?
The Case:
$("a").click(function(event) {
alert(event.type);
});
in C the function should be defined:
void click(fn,event){
}
in javascript its looks to me that she defined as- (but where defined event?):
click (fn){
}
please explain to me the jquery syntax of click function code source here.
Thanks,
Yosef
If you just want to find out where the event object is passed to your handler, that would be line 2568 of the jQuery-1.5.2 redistributable source code (or line 438 of the actual, un-contatenated source file):
var ret = handleObj.handler.apply( this, args );
In the above line of code, handler is your anonymous function and args is an array whose first element is the event object. jQuery uses the apply method of the JavaScript Function object to invoke the handler and pass in the arguments
The jQuery source code is quite complex when it comes to full sequence of adding and handling events so, unless you want a line-by-line explanation of hundreds of lines of code, I suggest you rephrase your question to a smaller scope (e.g. You could create a toy demonstration of the scenario you want to understand).
Perhaps this will help?
dosomething(function(message) {
alert(message);
});
function dosomething(fn) {
fn("Hello!");
}
The first part of the jQuery is the selector $("a") which selects and returns object(s) selected from the DOM. In this case, it will return a list of all anchor tag objects on the page.
Then, you are chaining the .click() method to that, jQuery attaches an event listener to all of the anchor tags. When the event listener is attached, it is more or less the equivalent of doing
<a href='..' onclick='someFunction(event)'>some link</a>
...which passes the event object to the function.
For example, compare to this:
<a onclick='blah(event)'>click</a>
<script type='text/javascript'>
function blah(e) {
alert (e.type);
}
</script>
If I click on it, I will see "click" in the alert. In principle, jQuery is doing the same thing.