i was reading those few lines of code from a javascript(Jquery) file and I was wondering where those arguments "x" and "y" are coming from.Is the scroll event that is taking care peraphs?
$(window).scroll(function(x,y) {
dosomething(withThis);
});
thanks
Luca
P.S. here is the jquery excerpt that made me ask this question Is this an elegant way to make elements fade in while scrolling?
Well, open Firebug console (or web dev. tools) and paste there this code:
$(window).scroll(function(x,y,z) {
console.log(x,y,z)
});
After execution and scrolling you'll see the result (works on sites with jQuery).
As expected, first argument - event object, 2nd and 3rd - undefined;
But, you can trigger events manually, and pass any arguments.
More info here: http://api.jquery.com/trigger/
No, the handler for the scroll event takes only an event object, not x,y. That code is misleading and wrong. We can't help if you don't show the full code.
This is the same thing as if you define a method
function add(a,b) {
return a + b;
}
// When called like this, b will be undefined, as is y in your example
// programmer error not caught by the compiler
add(7);
You could inspect the arguments variable on any function, so you can get an idea of the data that's passed in.
$(window).scroll(function() {
console.log(arguments);
});
Related
This is one of the first time's I'm looking at javascript, so please excuse the newbish question.
I'm trying to read the code for a specific function on a website that is of interest to me. I didn't write anything for the website, so cannot really comment on the general structure. This is almost like reverse engineering. Where it's called (in a js/main.js) looks like:
$(document).ready(function() {
$('#search').funcA();
From what I understand this is saying from the file/class or whatever that comesf rom the id search, call funcA. My questions is: how do I see the file that is called with #search?
funcA is almost certainly a jQuery plugin (or part of jQuery itself). The first thing I would try in your situation is searching for "jQuery funcA" on Google.
Whether or not it is actually part of jQuery, you can see the source for that function by running:
$('#search').funcA
in a REPL, such as your browser's console, or:
console.log( $('#search').funcA );
as long as the toString function for that function hasn't been overwritten and it is not a reference to a native function.
funcA appears to be defined as a jQuery method; try
console.log($.fn.funcA)
Open javascript console in the same browser window (I used chrome) that is displaying the page that contains that code. Then just execute this line:
> $('#search').funcA
You should see the body of funcA. Random example output when I did $("#myownid").show:
function funcA (a,b,c){var d,e;if(a||a===0)return
this.animate(cu("show",3),a,b,c);for(var
g=0,h=this.length;g
...
If you manage to see the body of the function, you should be able to infer likely sources (or post them here and we should be able to point you further)
The console.log suggestions here are nice use of Function.prototype.toString (and in some browsers some console magic), but I'd use debugger instead. Chrome has quite nice debugging tools for stuff like this and the debugger statement will get you there with ease.
var test = $('#search').funcA;
debugger;
Open the console and start investigating. When the execution of your code hits that breakpoint, you'll see handy tools like this
Right-clicking test there should also give you the option to "Show function definition" which will show you where the function was actually defined as source code.
And if you want to investigate even further from there, you can always set similar breakpoints right from the Chrome dev console.
Short version: Open the console and run $("#search") it will return a jquery object containing the dom node that has an id of search.
Long version:
$("something")
Is jquery (a java script library) for select elements by css selector returning a jquery object.
https://learn.jquery.com/using-jquery-core/selecting-elements/
$(document).ready(function() {
Is jquery for when my document (basically the page) is ready for me to muck with run this anonymous function.
https://learn.jquery.com/using-jquery-core/document-ready/
$('#search').funcA();
Selects a set of elements, in this case the single element with id "search" and then run funcA on each of them using the element as the scope. So it would run funcA on the element with ID "search" with the search node being the value of the special scope variable (scope is referenced through the key word "this", it can get rather complex).
So in essence what your seeing is:
When my document is ready find the search element and run my function funcA on it.
OK, so here's what I'm trying to do:
I'm building a Javascript->Cocoa/Objective-C bridge (a tiny test actually), which means that I'm able to call an Objective-C function from my JavaScript code.
One of the issues faced is that messages/errors/logs/etc from console.log are not visible, so they are to be forwarded to the corresponding Cocoa function (i created one like - (void)log:(NSString*)msg which simply takes a parameter as string and prints it out in the Xcode's console window.
Now, the thing is how do I replicate 100% what console.log does + forward the message to my own log function?
This is what I've done so far:
Javascript
console.log = function(text) {
API.log_(text);
}
Objective-C
- (void)log:(NSString*)msg
{
NSLog(#"Logging from JS : %#", msg);
}
If "text" is a simple text string when calling console.log("something"), then it works fine. If I pass the console.log function an object, then it's not working as expected (e.g. in Chrome's Javascript console window).
How would you go about it?
Is it possible to get the string output of what console.log would normally print out?
P.S. I tried playing with JSON.stringify(obj, null, 4) a bit, but it still doesn't seem right. Any ideas?
It sounds like you want the original functionality to persist whilst also capturing the input and passing it to your API. That could be achieved by something like (JSFiddle):
var original = console.log,
API = {
log_: function() {
// Your API functionality
}
};
console.log = function() {
original.apply(console, arguments);
API.log_(arguments);
};
A couple of things to point out. Firstly, the native console.log can receive any number of parameters, so we use arguments to handle this. We have to use .apply() to call the original method in the context of console and it also allows us to pass the arguments exactly as they were on the original call.
I have what looks like to me to be a simple variable assignment not working.
This code is in jQuery, for the context see here.
I'm calling:
$('#foo').on('someEvent', eventHandlerFn);
And I get this issue within the jQuery on function. Here's the starting point:
As you can see from the console below the code, selector is set the my eventHandlerFn and the fn variable is undefined. This is as expected.
On line 3509, the value of selector is assinged to fn. So, the value of fn should be same as the value of selector, no??
See below - selector is defined, as expected, but fn is still undefined. Why?
The end result is that my event handler is never registered.
The code runs well as shown in the following two screens (the issue is on how chrome sets the context to the console)
It looks like console has access to the variable at definition time (in this case the passed parameters) and not the live values as you run the code
Before the swap
After the swap
I'm not seeing any problem with this jsFiddle. Feel free to edit the jsFiddle to get it to look more like your code.
Can you try putting in console.log(fn); after line 3510 and rerunning? Maybe it's just a problem with the debugger?
This seems to be an issue with the debugger in Chrome - either a material problem or just a nuance of the debugger that I don't understand. fn does have a value toward the end of the call, but not where the breakpoint is.
I'm updating an existing website running on Expression Engine. So far, I've stayed away from any code I didn't write or couldn't understand. I recently must have altered some bit of code someplace (helpful, I know) and now a block of JS I didn't write is causing an error that seems to bypass the document.ready() event. The window.load() event however is still taking place.
In the Chrome DevTools Console, the error "Uncought TypeError: Cannot call method 'replace' of UNDEFINED" points to the definition of a function "fixedEncodeURIComponent" pasted below.
$("#MessageContainer.Counted").counter({
type: 'char',
goal: 250,
count: 'down'
}).change(function(){
var TEMP = fixedEncodeURIComponent($(this).val());
$("#Message").val(TEMP);
});
var TEMP = fixedEncodeURIComponent($("#MessageContainer.Test").val());
$("#Message").val(TEMP);
function fixedEncodeURIComponent (str) {
str=str.replace(/"/g, '');
return encodeURIComponent(str).replace(/[!'()*]/g, escape);
}
As I interpret the error, this function is being passed a variable that is not a string. I added an alert(str) to the function definition and the result was UNDEFINED as I expected. The first of several unknowns for me is which call to the function 'fixedEncodeURIComponent' is being passed a bad variable. I assume that it's the first call, but that's just a guess. It so happens that this first call contains a syntax I have never encountered before. I don't know how to interpret what happens when $(this) is passed as a function argument.
Any insights would be greatly appreciated. Also, if there's more information you need please let me know. The client's site is password protected but I can include any code you request.
Thank you.
I'm taking a guess that the }); on line 3 is exiting a document.ready context. If that's the case then your second call to fixedEncodeURIComponent may be getting called before the DOM is even loaded.
Start by wrapping
var TEMP = fixedEncodeURIComponent($("#MessageContainer.Test").val());
$("#Message").val(TEMP);
in a
$(function() {
// code
});
block. If that doesn't work, check that #MessageContainer.Test actually matches an element. Since this is code you inherited, the class name "Test" clues me in that the block in question might be a remnant of someone trying to debug an issue and maybe it should have been removed.
I suspect $("#MessageContainer.Test") since it looks like its supposed to be an ID selector instead of what it actually is when jQUery parses it(which is an ID selector combined with a class selector). $("MessageContainer\\.Test") allows you to select an element with ID MessageContainer.Test
I am trying on some code here,
var cat={
col:"Red",
getCol:function(){
document.writeln(this.col);
}
}
function getCol(){
document.writeln(cat.col);
}
$(function(){
$("#button1").click(cat.getCol);
$("#button2").click(getCol);
})
But I got undefined for button1, "Red" for button2. Can someone tell me why?
And if I change it into $("#button1").click(cat.getCol());, I got the "Red" I need...
First of all
$("#button1").click(cat.getCol);
gives you undefined because the body of cat.getCol uses this which ain't cat when this thing runs. I would suggest using Function.prototype.bind here, or several of the other variants if you are worried about cross-browser compatibility. There are many published solutions to the problems of setting "methods" as event handlers and ensuring that this stays bound to the enclosing object.
Next
$("#button2").click(getCol);
works fine because getCol uses cat directly.
Finally
$("#button1").click(cat.getCol());
is terribly wrong. The expression cat.getCol() is a call which returns undefined. This is not a good value to set for a click handler. You just saw the document.write taking place, but not in response to a click.
ADDENDUM
Live demo using bind
Generally in JS, this refers to the owner of the function .. So, in both cases when that function is called, this would resolve to the (jQuery object of the)element that has been clicked.
In the first case, this is not 'cat', so col is not defined. Thus, it gives undefined.
In the second case, no this, so cat.col resolves to Red.
I think you need to do some reading about JS functions, this, anonymous functions .. http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/ is a good place to start.
This on MDN - https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/this