what's the meaning of the functions in javascript? - javascript

function ExChgClsName(Obj,NameA,NameB){
var Obj=document.getElementById(Obj)?document.getElementById(Obj):Obj;
Obj.className=Obj.className==NameA?NameB:NameA;
}
<a href="javascript:showMenu(2);">
i am a newbie of the js. so can't understand the above two function very well. expect someone can explain the line's meaning to me one by one. many thanks.

For the first function
var Obj=document.getElementById(Obj)?document.getElementById(Obj):Obj;
The first line gets the object by its ID if Obj is a string that is the ID of a DOM element. Otherwise it leaves the value of Obj alone. This is using the "ternary conditional" operator, a? b: c. which as a value of b if a is truthy and c otherwise. Doing this allows the function to accept a string or a DOM element.
Obj.className=Obj.className==NameA?NameB:NameA;
The next line sets the CSS class of the DOM element from the last line to NameB if the CSS class of the DOM element is NameA and otherwise sets it to NameA. This would have the effect of swapping out the classes so long as another class is never assigned to the element. If another class is assigned to the element, then it will start the cycle again with NameA.
function showMenu(iNo){
ExChgClsName("Menu_"+iNo,"MenuBox","MenuBox2");
}
The second function just applies the first to swap the CSS class of the the DOM element with ID of "Menu_"+iNo between "MenuBox" and "MenuBox2".
Personally, I don't like the first line of the first function because it does two searches of the DOM when it only needs to do one. I would do this
var Obj = document.getElementById(Obj) || Obj;
That should be more efficient on all implementations and is surely more readable. It uses the || operator as a guard to assign Obj back to itself if only if document.getElementById returns null.

Exchange the cascading style sheet class name on an object from A to B
Find the element
if the object's css class name is nameA, set it to nameB, otherwise, set it to nameA

function ExChgClsName(Obj,NameA,NameB){
//ternary operator, sets Obj = the dom object with id = 1st agrument if it exists
//you can get away with this because an object is "truthy" in javascript
// truthy meaning that if you try to evaluate it as a boolean it is the same as true
// if nothing is found getElementById returns null wich is the same as false
var Obj=document.getElementById(Obj)?document.getElementById(Obj):Obj;
//ternary operator again. changes the class of the dom object to the 3rd argument
//if its class is already the 2nd argument
//otherwise it changes it to the second argument
Obj.className=Obj.className==NameA?NameB:NameA;
}
function showMenu(iNo){
//calls exChgCLsName with the specified arguments
ExChgClsName("Menu_"+iNo,"MenuBox","MenuBox2");
}
// Runs the showMenu function when clicked
<a href="javascript:showMenu(2);">

Related

What are the values that can be assigned to variables in javascript?

In all programming languages "variables" can be defined as follows :
"They are reserved places in RAM to store data"
Turns out that such code is logical in javascript:
var x = document.getElementById("IdName");
x.innerHTML = "Hello Stack Overflow";
Or This Code:
var x = alert("Hello Stack Overflow");
I don't get it, Of course alert() and document.getElementById("")
aren't data to be assigned to variables
I want someone to explain why such thing is possible.
I'm really confused of this.
No, document.getElementById("IdName") "isn't" data; it's a function call that returns data:
Returns a reference to the element by its ID [...]
Syntax
element = document.getElementById(id);
Parameters
id
is a case-sensitive string representing the unique ID of the
element being sought.
Return Value
element
is a reference to an Element object, or null if an element with the
specified ID is not in the document.
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
The function call returns an object of type Element (or null), which is data a value that can be assigned to a variable. This works pretty much exactly the same in virtually all programming languages. Values can be assigned to variables. Functions return values.
alert() does not happen to return anything, which means it implicitly returns undefined, so the value undefined will be assigned to x. That is a rather useless operation, but still works by the same rules.

difference in jQuery object context

I'm trying to obtain some insight in the context of a jQuery object. I've read a ton of questions on SO, but they all want to fix a specific problem, and the answers thus fix the problem, and didn't really provide me with the knowledge I'm hoping for.
So I have two buttons, and I have a click event that listens for both of them like so:
$('#copyRI, #copyIR').click(function () {...}
Now when I try to establish which element was clicked like so:
$('#copyRI, #copyIR').click(function () {
var test = $(this);
var test2 = $('#copyIR');
var compare = (test === test2);
}
compare returns false when I click the button with id = #copyIR
when debugging I noticed that the context of test and test2 are different:
Now I'm not looking for a way to successfully establish which button was clicked, but I want to obtain some insight in the concept of the "context" in a jQuery object.
Thanks in advance!
When you call $(this) you create a new jQuery object, instantiating it with an HTML Element.
When you call $('#copyIR') you create a new jQuery object, instantiating it with a selector. This stores extra information in the object, including the selector itself.
Even if that wasn't the case, you would be creating two different objects and === (and == for that matter) test if two objects are the same object not if they are identical objects.
$(this) === $(this) would also return false.
If you want to test if the elements are the same, then you can compare the underlying DOM nodes (since those will be the same object)
var compare = (test[0] === test2[0]);
Alternatively, you can just test if the object you have in the first place matches the selector:
var compare = test.is('#copyIR');
You should rather use .is() method here.
Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.
CODE:
$('#copyRI, #copyIR').click(function () {
var test = $(this);
var compare = test.is('#copyIR')
}
jQuery contexts (being an Object) are compared by reference, so test === test2 would obviously return false since each variable is pointing to a different jQuery context (the fact that both contexts internally contains a reference to same DOM object doesn't matter).
Try is() instead:
var compare = $(this).is('#copyIR');
See Documetnation
You could simply compare the id.
$('#copyRI, #copyIR').click(function () {
if (this.id === 'copyIR') {
// do something
}
}

Javascript Object Passed Into Method Is A String

I'm building a phonegap project using jQuery mobile.
I have a javascript object that I'm iterating through.
Currently the problem is this:
Below is a method in my model object. It is self recursing, and once called, will recurse through itself to the next level every time a user clicks on a list item generated by the previous level of the object.
What I am battling with is passing the iterated segment, b, into the method itself as an object. For some reason this is returned as a string called [Object], and not the object itself.
This function does work as it's displaying the first level, but something about the "firstString" string I am creating for each child seems to be turning my object into a string named object. I have removed the quotes, placed the object in braces, to no avail.
Would anyone have any idea why this is happening, I'm obviously missing something important regarding passing objects into methods whose call is generated as a string...
My code is below, and line causing the issue is firstString+="model.recurseAppTree('"+b+"');";
recurseAppTree: function(AppTree)
{
$.each(AppTree, function(a,b)
{
var firstString='<li data-role="list-divider" role="heading" data-theme="b">'+b.DisplayValue+'</li>';
if(b.Children != null)
{
$.each(b.Children, function(c,d)
{
firstString+="<li data-theme='c'><a data-transition='slide' id='id-"+d.IdValue+"' href='javascript:void(0);'>"+d.DisplayValue+"</a></li>";
firstString+="<script>";
firstString+="$('#id-"+d.IdValue+"').click(function(){";
firstString+="model.recurseAppTree('"+b+"');";
firstString+="});";
firstString+="</script>";
});
}
$("#selectview").html(firstString);
$("#selectview").listview('refresh', true);
});
},
It's just normal.
You use an object in a string context by the concatenation with +. This tells JS to implicitely cast the object to a string.
b = {}
alert(typeof b) // object
alert(typeof (''+b)) // string
You should use event delegation for your gui
1- Add a (common) class to your '' tags, e.g. unrollLink :
var firstString='<li ...><a class="unrollLink" ...></a></li>"
2- Choose a node in your html, which is a parent of all your "tree" nodes, and will always be present in your html. Delegate the click handler to this node :
$('#selectview').on('click', '.unrollLink', function(){
//this === clicked link - write a function which returns the node you want based on the "id" you set
var myNode = getNode( this.id );
model.recurseAppTree( myNode );
});
3- change your function to produce the adequate html. You don't need to add code for the click events :
recurseAppTree: function(AppTree)
{
$.each(AppTree, function(a,b)
{
var firstString='<li data-role="list-divider" role="heading" data-theme="b">'+b.DisplayValue+'</li>';
if(b.Children != null)
{
$.each(b.Children, function(c,d)
{
// add the class you chose to the clickable items :
firstString+='<li data-theme="c"><a class="unrollLink" data-transition="slide" id="id-'+d.IdValue+'" href="javascript:void(0);">'+d.DisplayValue+'</a></li>';
});
}
$("#selectview").html(firstString);
$("#selectview").listview('refresh', true);
});
},

jquery attr(name,value) method's value parameter

I'm reading Bibeault's jQuery in Action and I'm having troublel understanding the value parameter of the attr() method. The book says that the parameter can be a function whose parameters are index and previousValue. What is the purpose of these parameters? I don't understand the text's explanation.
Specifically I want to know:
Are these parameters mandatory?
What is an example of how these parameters are used?
Can I use other parameters within the function?
1) No parameters are mandatory in javascript. You use whatever amount you want. These parameters are available for you in your function.
2) examples:
Let's say you have this html:
Now, run this snippet:
$('a').attr('title', function(index, previousValue){
return previousValue + ' - An external link';
});
This will add the string " - An external link" to the end of every title.
Now, look at this:
$('a').attr('title', function(index, previousValue){
return previousValue + ' - Link number ' + index;
});
This will result in the following html:
As you can see, you can see, these parameters are very handy.
3) Not sure what you mean by using other parameters. Please clarify.
It seems that you are not familiar with Javascript's scope lookup chain. You do not have to explicitly pass parameters to a function. If they're defined in a scope above it, the function will have access to it:
var num1 = 23;
var num2 = 54;
$('a').attr('title', function(){
return num1 + num2;
});
It's actually pretty simple. The attr() function has three possible modes; the one you refer to takes a callback to get the value.
For example:
$('.someClass').attr('rel', function(index, value)
{
// index refers to the elements index of the set; so of all elements with the
// css class 'someClass', the index will refer to that position in the list.
// If three elements match, the callback will be invoked 3 times, with 0, 1, 2
// as the index when each element, respectively, is invoked.
// value refers to the current value of the attribute.
// Return the value you want to set.
return 'SomeRelValue';
});
The parameters are not mandatory; if you simply omit them from the callback signature, you simply dont have access to that information. You cannot pass other parameters to this method. You might want to use this function when you will match a lot of elements, and want to insert some data based on their ordinal position of the selector element.
For example:
$('.someElements').attr('rel', function(index, value)
{
return value + index;
});
For each element matching the selector, you set the rel attribute to what it was plus the index of the selector. So element one, if it had a rel of 'sampleRel', is set to 'sampleRel1', element two with rel' sampleRel' becomes 'sampleRel2', etc etc
There's a good example in jQuery's documentation, which I'll shorten here:
Here's the relevant HTML:
<div>Zero-th </div>
<div>First </div>
<div>Second </div>
If you then run this javascript it'll apply unique id's to each div:
$("div").attr("id", function (arr) {
return "div-id" + arr;
});
The $ function returns all of the div's so the arr argument allows you to specify the attribute value based on the index.
The function passed to attr also received a value specifying the old attribute value, but as this is javascript the function doesn't have to name that argument and it's still available in the arguments.
attr is a way to access attributes on an element. the overload which allows a function will allow you to use the function return to set the value (the index param to the function would be the index into the selection, previousValue being the value it had until now).
I've never used this overload myself, but assume it would be nice if you're making attribute values based on some sort of function.
They are not mandatory, passing different number of parameters gives different functionality:
attr('name') - gets the value of name
attr('name','value') - sets the value of name
attr('name',function(i,v){return v+i;}); - sets the value of name to the previous value + the index in the collection.
example:
lets say we have five spans with the class hiccup and name 'yup'.
$('span.hiccup').attr('name',function(i,v){return v + i;});
will give each span a name 'yup1' - 'yup5'.
Additionally, you have access to this inside the function, which refers to the element itself. Given this, you could probably do some really interesting stuff.
As always, jQuery has awesome documentation of all of this:
http://api.jquery.com/attr

What does this mean?

function fkey(a) {
a || (a = {});
if (!a.fkey) a.fkey = $("input[name='fkey']").attr("value");
return a
}
I guess a is actually a function, but how to understand (!a.fkey) ?
a is an object in this case, it's setting the .fkey property on it if it isn't set (or is falsy) already.
For SO chat, this allows the fkey input to either be provided or gotten from the page, it's a hidden input at the bottom of your page, populated with a value used to authenticate your request and such.
Currently it's always pulling from the DOM, so really this function just adds the property, it would leave it alone if it were provided though.
a is not a function, it's an object.
The a.fkey is accessing a member of the a object. The ! in front means that if the member does not exist or the value is falsy, the expression evaluates to true and the fkey member is set to $("input[name='fkey']").attr('value');, which can also be accomplished with .val() instead of .attr('value')
The function you posted adds a member named fkey to a if it did not already exist. The !a.fkey part essentially means "does not already exist" (this works because once assigned, the member does not evaluate to false).
The function takes an object and adds an fkey property to it, which will be the value of
<input name="fkey"> field.
For example:
<input name="fkey" value="WATCH ME HERE">
var temp = {}; // make a new object
fkey(temp); // expand it with fkey's value
alert(temp.fkey); // WATCH ME HERE

Categories