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.
Related
I am a beginner in javascript. and have no experience in programming, at all.
So I'd like you to be generous to beginner.
And here is my question.
I'm trying to code javascript unobtrusively.
So I put in all of my js codes into external js file. for example : test.js
and deleted these codes. to do unobtrusive js coding. for example :
and I tried to use these 2 methods :
variable.onclick=test(arg1, arg2);
variable.addEventListener('click',test(arg1, arg2),true);
but these triggers didn't work.
to put it delicately, function test(arg1, arg2) worked right after dom loding finished. regardless of activating 'click' trigger.
So I spent several hours solving this problem, and finally got a solution. this is it.
variable.onclick = function(){
variable.addEventListener('click',test('arg1','arg2'),true);
}
I wanna know why first two methods didn't work, and why that solution works well.
I solved the problem, but don't know why, and how...
In JavaScript, when you reference a function by name and follow that reference by a parenthesized list of arguments, that means that you want to call the function, right then and there. Thus a statement like
variable.onclick=test(arg1, arg2);
will assign to the "onclick" property the value obtained by calling the "test" function. In other words that statement means
Please call the function "test" passing it "arg1" and "arg2", and assign whatever it returns to the "onclick" property of the object referenced by "variable".
An event handler must be a function, however, and your "test" handler probably returns either nothing, or something that's not a function. So it didn't work.
Your solution, however, is also incorrect. You're successfully assigning a function to the handler property, but your function is itself installing another event handler. There's no reason to do that here, and in general setting up event handlers from within other event handlers is a suspicious practice. All you need is:
variable.onclick = function() { test(arg1, arg2); };
variable.onclick requires a function declaration by design. In your case you could have just done
variable.onclick = function(){
test(arg1,arg2);
};
The way you did it won't work because you're not giving the click handler any instructions. The corrections I have made say that when the variable (the one with the click handler attached) is clicked trigger this function that will in turn trigger the test function.
Same thing goes for the second one
variable.addEventListener('click', function(){
test(arg1,arg2);
});
This works again because you are saying when this variable is clicked run the function that will trigger the test function.
Basically you are trying to assign the result of running a function, the test function as a task for the click handler to run. This won't work except maybe your test function returns a function that contains code that you want to run when the click event is triggered. Hope this helps.
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 am working on someone else's code and came across something puzzling.
Rather than calling functions the code is calling binding functions and then triggering it through a string.
Example 1:
bind("hello.world", function(){
console.log("hello world");
});
trigger("hello.world");
Rather than ---
Example 2:
helloWorld = function(){
console.log("hello world");
}
helloWorld();
What are the pros and cons between Example 1 and Example 2. Thank you.
Well, since javascript is an event driven programming language, I would recommend the first one.
Here's a case that illustrates the advantages of using event-handlers instead of simple function calls :
function someEventHandler(){
if($(this).hasClass('some-class'))
// do something
}
$('element').bind('eventName.eventNamespace',someEventHandler);
Now, if you simply call this function such as :
someEventHandler();
you can see that it will have no effect, because it is designed to be executed in a dom element context.
If you trigger the event that has the someEventHandler function as it's event-handler :
$('element').trigger('eventName.eventNamespace');
the function is called in the element context, something like :
someEventHandler.call($('element').get(0));
which will have the desired effect.
Moreover, you can bind multiple event-handlers to the same event and bind it to multiple elements.
If you would like to call a function for each of a list of dom elements, you would have to do something like this :
someEventHandler.call($('element1').get(0));
someEventHandler.call($('element2').get(0));
someEventHandler.call($('element3').get(0));
// ... and so on
while, with the first method would much more easier :
$('element1,element2,element3').bind('eventName.eventNamespace',someEventHandler);
$('element1,element2,element3').trigger('eventName.eventNamespace');
Note that the approach you take depends on the context you're using these functions. If your function has nothing to do with a dom element or you do not want more objects to subscribe to your event, you probably should keep it simple and use classic function declarations and calls.
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.