Transversing a JQuery object? - javascript

I'm doing sorting of a list of elements, using:
jQuery.fn.sort = function() {
return this.pushStack( [].sort.apply( this, arguments ), []);
};
$("ol li").sort("sortFunction").appendTo("ol");
The problem is in the sortFunction.
function sortFunction($a, $b) {
...
}
Basically, what I want is to treat both $a and $b as jQuery objects, so I can manipulate them.
e.g, inside the sortFunction do
$a.find("div#3 li").html();
This doesn't work since $a and $b are native javascript objects.
Any help?

They are native DOM elements. You can call the jQuery function on one to wrap it, so that the jQuery functions are available:
$($a).find(...)

You can turn a native JS object into a jquery object like this:
var jsObject = $(nativeobject);
Does that help?

Can't you simply call jQuery on the objects?
function sortFunction($a, $b) {
var jQueryA = $($a);
}

Just turn them into jQuery objects in the sort function:
$($a).find("div#3 li").html();
Note: don't call them $a but just a. Prefixing with the dollar sign generally indicates a jquery-type variable so it gets confusing if it is not

Related

jquery variable vs $(jquery varibale), what is difference b/w the two

When I do:
var x = $("#listing")
I get back html element with id listing,
And when I do $(x) or $($("#listing")), I get the same.
What is difference b/w two?
$() will convert something to a jQuery object (or collection). This is not the same as a Javascript variable.
When you store #listing in a variable such as var x = '#listing', you are simply passing a string to the jQuery constructor, which is then interpreted as a selector by Sizzle, jQuery's selector engine.
In the example provided, there is no difference between the two following lines:
var x = $('#listing');
var x = '#listing',
$x = $(x);
In the first snippet, x is identical to $x in the second.
In the interest of completeness, the jQuery constructor can also accept a mixed type variable as its first parameter; it doesn't have to be a string. For example, it's possible to convert a DOMElement variable into a jQuery object using the following syntax:
var ele = document.getElementById('myItem'),
$ele = $(ele);
Notice that $ele now has access to jQuery's own functions, such as addClass(), etc. Please see this demo.
Furthermore, passing a jQuery object to the constructor will simply return the same jQuery object. For example, given the following snippet:
var $x = $('#listing'),
$x2 = $( $x );
$x is identical to $x2.
Your x variable was made a jQuery object once it found the dorm item.
Once you run var x = $('#listing'); x has everything wrapping it has.
Thus you can run x.addClass('thing')
Adding $ is creating jQuery object, its not normal variable. You can create jQuery object from DOM element, from another jQuery object or from normal javascript variable. Try to run console.log(x) console.log($(x)) and it will tell you all differences.

.append or .after defined as a variable?

So I'm trying to figure out the best way to get this to work. I have a long list of code that's pulling off of a JSON database, and I'm trying to streamline it. I've created the following function:
var insertData = function(formattedData, originalData, referencePoint, insertPoint, insertStyle) {
var formattedData = originalData.replace("%data%", referencePoint);
$(insertPoint).insertStyle(formattedData);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
Is it possible to define a dot function similar to how I have it here - referenced as one of the function's variables? This current code says that insertStyle is not a function - how do I get the code to recognize that insertStyle should be taking a variable name? As in, if my fifth variable called by insertData is append, it should be read as .append.
As a reference, here's how I'm calling the function:
insertData("formattedHeaderName", "HTMLheaderName", bio.name, "#header", "prepend");
Thanks for any assistance or thoughts in advance!
You're looking for a computed property:
$(insertPoint)[insertStyle](formattedData);
Basically, every property access can be represented as a computed property:
foo["bar"]; // same as foo.bar
In your original code, you're using a non-computed property so the interpreter looks for a method literally called "insertStyle", which doesn't exist.
When you pass an argument to a function, like you do in:
insertData("formattedHeaderName", "HTMLheaderName", bio.name, "#header", "prepend");
Those arguments are strings. Not jQuery methods.
So, a solution would be to define all the methods you need to use...
And just compare the string passed to decide.
var insertData = function(formattedData, originalData, referencePoint, insertPoint, insertStyle) {
var formattedData = originalData.replace("%data%", referencePoint);
if(insertStyle=="prepend"){
$(insertPoint).prepend(formattedData);
}
if(insertStyle=="append"){
$(insertPoint).append(formattedData);
}
if(insertStyle=="after"){
$(insertPoint).after(formattedData);
}
// And so on...
}
Maybe there is some other ways to achive this...
But this one is quick and easy to implement.

Understanding a JQuery complex chaining code example

I want to understand the meaning of the $ sign when added to the beginning of a variable and why we have to wrap the item variable with the $ sign ? in order to change a text value.
For this line of code:
var $item = $(item);
I think that $item is like any other variable ?
I have this short JQuery code:
var items = $('#special-features li');
items.width('50%')
.height('200px')
.addClass('hightlight bordered')
.each(function(index, item){
var $item = $(item);
$item.text($item.text() + ' ' +
$item.attr('data-features-id'));
});
Here is the result of the code above
The code is just caching the $(item) object. As it is used multiple times it's better practice to cache the object instead of referencing from DOM which will improve the performance slightly.
var $item = $(item);
$item.text($item.text() + ' ' +
$item.attr('data-features-id'));
The $ in $item is just a variable name. It is common practice to use $ at the beginning of variable that contains jQuery object.
$ is a shorthand of the function jQuery. Since jQuery it's a simple javascript function, then when you call $() you just execute function and return the result to the variable and result of this function is jQuery object element.
$ before variable names it's just convention how to higlight jQuery objects in the code.
And about chaining. In all methods in your example return value is the same object on what you apply this method. It's basically how chaining works.
Hope it answers all your questions.

How to make variable as callable function?

I have two variable and one function.
<script>
function myfunction(a1,a2,a3)
{
alert(a1+a2+a3)
}
var fname="myfunction";
var fdata="data1,data2,data3";
</script>
I want to call function from variable values. like this
myfunction('data1','data2','data3')
I know how to call function from variable value.
window[fname](); //this call myfunction()
But don't know how to call function with multiple arguments from variable values?
Give me a solution if you can!
First, you don't have to use the name of a function to keep a reference to it. Just use the function directly:
var fname = myfunction;
Then you can call it:
fname('whatever');
To pass parameters from that string, you'll have to get them out of the string, a process that will depend on how you've combined the values into a string in the first place. In your example, you could split the string on commas to create an array, and then use .apply()
fname.apply(null, fdata.split(','));
The .apply() method accepts an array as the second parameter (the first is a value to be used for this), and then calls the function such that the values of the arguments are the elements of the array.
Just add the arguments between the parentheses
window[fname]('data1', 'data2', 'data3');
To pass dynamically the arguments by using the fdata value, you should use apply (like #Pointy suggests).
window[fname].apply(null, fdata.split(','));
you can modify your code to be something like this maybe:
<script type="text/javascript">
function myfunction(a123) {
// remove the coma if you don't want it.
var completeData = a123.replace(/,/g, "");
alert(completeData);
}
var fname = "myfunction";
var fdata = "data1,data2,data3";
window[fname](fdata);
</script>
I hope it helps.

Javascript ternary operators for method calls

I would like to be able to do this:
var b = $(this).is(':checked')
$('.perspective-col'). (b) ? show() : hide()
instead of
var b = $(this).is(':checked')
if(b) {
$('.perspective-col').show()
} else {
$('.perspective-col').hide()
}
Am I wishing for too much? Or is there some wonderful javascript syntax I haven't found yet? Or am I right in thinking that no such thing exists in JQuery thus far? (I'm using JQuery 1.9.0)
You can use this :
var b = $(this).is(':checked')
$('.perspective-col')[b ? 'show' : 'hide']()
You can call jQuery function by passing a string into the bracket []. Just insert a condition inside to decide which string you pass!
In general,
<any expression>.property
is equivalent to:
<any expression>['property']
The difference is that you can replace the literal 'property' in the brackets with an expression that calculates the property name. jQuery methods are just properties whose values happen to be functions.
But I actually hate that practice. You can also use jQuery .toggle()
jQuery has a method that does what you want called toggle():
$('.perspective-col').toggle(b);

Categories