What is the difference between "$(this)" and "this"? - javascript

I was reading the http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery. And got confused with use of this in these 2 code segments.
$(document).ready(function() {
$("#orderedlist").find("li").each(function(i) {
$(this).append( " BAM! " + i );
});
});
$(document).ready(function() {
// use this to reset several forms at once
$("#reset").click(function() {
$("form").each(function() {
this.reset();
});
});
});
When do we need $(this) and this? And what is the difference between them? Thanks in advance.

this refers to the DOM element itself; $(this) wraps the element up in a jQuery object.
In the first example, you need $(this) because .append() is a jQuery method.
In the second example, reset() is a JavaScript method, so no jQuery wrapper is needed.

this by itself is just a regular object.
$(this) takes this and adds the jQuery wrapper so you can use the jQuery methods with the object.

this refers to a DOM object. So reset() is a function of a form DOM object. append() on the other hand is a jQuery method so it has to be called by a jQuery object, hence the $(this).
When you surround this with $, you get a jQuery object back representing that DOM object.

Generally in jQuery, this will be an instance of the DOM element in question, and $(this) builds a jQuery object around this which gives you the usual jQuery methods like each() and val().

you only need $(this) if you are following it with a jquery function on the same line of code.
ex: $(this).find(...); $(this).val(); etc
or else you only need this.

Related

How to examine parentNode classList in an if else statement in javascript

I have a function which is called whenever a checkbox is clicked from a particular group.
I am trying to add a class to the input's parent wrapper when the checkbox is checked, and then remove the class when it isn't checked.
My problem is, I can't seem to get parentNode and classList working together.
eg. This code works:
$(this.parentNode).css( "border", "3px solid red" );
But this code returns an undefined error
alert($(this.parentNode).classList
For context, here's what I'm eventually trying to get to:
if ($(this.parentNode.parentNode).find('.form-type-checkbox').classList.contains("chkbox-checked")) {
$(this.parentNode.parentNode).find('.form-type-checkbox').removeClass("chkbox-checked");
} else {
$(this.parentNode).addClass("chkbox-checked");
}
I think the simplest solution could be like you should use toogleClass() of jQuery. Kindly refer the following code.
$("#id_of_radioButton").click(function(){
$("#id_of_parentNode").toggleClass("classname");
});
$(this.parentNode) is a jQuery object, as classList is pure JS property, this will not work on jQuery referenced object.
Try using jQuery's .attr():
$(this.parentNode).attr('class');
Don't blindly use jQuery for everything. this.parentNode.classList will be defined because it's not wrapped in jQuery, since classList doesn't exist in jQuery.

How is "this" used in this JS code [duplicate]

This question already has answers here:
What's the difference between '$(this)' and 'this'?
(7 answers)
Closed 8 years ago.
I've been reading quite a bit now, but I still haven't gotten a explanation that would make sense, from a noobs perspective.
$(document).ready(function() {
$("#slideshow").css("overflow", "hidden"); /*kuna JS t66tab siis ei ole vaja scrollbari n2ha*/
$("#slideshow-nav").css("visibility", "visible"); /*nupud tehakse n2htavaks*/
$("#slideshow-nav a[href=#pilt1]").addClass("active"); /*muudetakse esimene nupp aktiivseks*/
$("#slideshow-nav").localScroll({ /*see funktsionaalsus pärineb ka http://flesler.blogspot.com/*/
target:'#slideshow', axis: 'x' /*vajalik scrollTo ja localscroll kasutamiseks, paneb paika,et need pluginad liigutaksid slaidi pilte mööda x-telge*/
});
$("#slideshow-nav a").click(function(){
$("#slideshow-nav a").removeClass("active");
$(this).addClass("active"); /*kui vajutada uuele nupule v6etakse aktiivne klass sealt 2ra ja lisatakse vajutatud nupule*/
});
});
What purpose does $(this) have in context to this: $(this).addClass("active");, I understand what the code itself does, but what is the purpose for $(this), if $(this) wouldn't be used there, is there a easy way of achieving the same effect?
Thanks!
$(this) refers to the the jQuery element that was clicked. Using $(this) is a surefire way to ensure you're referencing the element that was the user interacted with. Unfortunately there is no good way to ensure that you're referencing the element you interacted with without using $(this)
First let's start with what this means. In JavaScript, any function can be bound so that this refers to an arbitrary thing (object, number, string, etc.) inside of the function when it's called (refer to Function.bind). In general there are no assurances of what this will refer to inside of an arbitrary function; you'll have to read the documentation/source code or test for yourself.
When you call click(), jQuery is binding this in your callback function to a target element in the matched set. When you say $(this) (or jQuery(this)), you're simply wrapping the element with a jQuery "wrapper".
As for alternatives, jQuery will pass the event object to your callback, and you can access the target through that:
$("#slideshow-nav a").click(function(evt){
console.log($(evt.target)); //I think just using "$(this)" is easier!
});
See jQuery $(this) vs this.
$("#slideshow-nav a").click(function(){
$("#slideshow-nav a").removeClass("active");
$(this).addClass("active");
});
When the handler function you passed to $("#slideshow-nav a").click() is called, this is bound to the element that fired the event. You then pass this to $() to construct a jQuery object around that element, so you can use jQuery's addClass() on it. You could accomplish the same thing by replacing that line with this.classList.add("active"), to use the non-jQuery way to do the same thing.
Long story short, you use $(this) when this is bound to some element and you want to use jQuery methods on that element.
So, what this code ultimately does is:
Remove the class "active" from all elements matching the selector #slideshow-nav a.
Add the class "active" to the element receiving the event (the clicked element).
In this manner, any previously "active" element is "deactivated", and the clicked one is "activated".
Per minitech's comment, $(this) refers to one of the 'a' elements in the slideshow-nav DOM element, specifically the one that was clicked.
$("#slideshow-nav a").click(function(){
// $("#slideshow-nav a") refers to an array of links in slideshow-nav
$("#slideshow-nav a").removeClass("active");
// $(this) refers just to the specific link that was clicked
$(this).addClass("active");
});
This is best practice AFAIK. Is there some reason you do not want to use $(this)?

How "this" works in jQuery

Can somebody please explain how "this" works in jQuery. I tried to find some information on the net, but because "this" is used a lot in his usual meaning I couldnt find anything good.
I would like to be able to change the background of a list element (<li>) onclick without giving each list element an id.
$('li').on('click.namespace', function() {
console.log(this); /* this is a reference to the DOM
element you clicked */
console.log($(this)); /* this is a jQuery reference to the
DOM element you clicked */
/* using jQuery reference you can change the background in this way */
$(this).css('background-image', 'url(...)');
});
$("li").click(function() {
$(this).css("background-color", "red");
});
Here is an example. $(this) refers to the JQuery object, this refers to the regular DOM object that was clicked on.
Did you find the click() documentation? It shows how you should use the click handlers and it has examples that even use $(this).
Here's an example:
$('li').click(function() {
$(this).attr("class", "clicked");
});
When one clicks on an item, this takes the value of the item being clicked on, that is the DOM element. $(this) gives you access to the jquery API.
If you set the onclick event on the li you can use $(this) to get the jquery object of the li, and then add a class eg. $(this).addClass("newBackground").
jQuery is kind enough to set the context of your function to the thing you're interesting in. In this case the <li> in question. But this is still a naked DOM element, you need to wrap it with $() to use jQuery methods on it.
$('li').on('click', function() {
$(this).css({background:'red'});
});
Sometimes you have to use a bound function (see jQuery.proxy()) as an event handler, in these cases you can access the current element differently, instead of this, you can use the event.currentTarget property, see http://api.jquery.com/event.currentTarget/

Using jQuery and standard JavaScript together

I have this line of JavaScript / jQuery that I'm attempting to use to append an element to the DOM and then attach an eventlistener to.
$('.faq_answer').prev().append(finalRender.cloneNode(true)).addEventListener("click", function () {toggle(this)}, false);
I know the appending part works perfectly but adding an event listener is giving me grief.
Is it possible / advisable to use jQuery and normal JavaScript together like this?
Or is there something in jQuery that would work better. (Very new to jQuery so bear with me).
If you want to use the native methods, then you need to call them against DOM elements, not jQuery objects
var clone = finalRender.cloneNode(true);
clone.addEventListener("click", function () {toggle(this)}, false);
$('.faq_answer')
.prev()
.append( clone );
If you want to use jQuery, then you need to wrap the DOM elements in a jQuery object.
// Drop your DOM element----v----into a jQuery object
var clone = $( finalRender.cloneNode(true) ).bind("click", function (){
toggle(this);
});
$('.faq_answer')
.prev()
.append( clone );
You could do something like this:
$('.faq_answer').prev().append(finalRender.cloneNode(true)).click(function () {toggle(this)});
which is pure jquery
I think you're wanting to add your event Listener to the cloned Node - not to the prev() of .faq_answer.
If you're importing jQuery, why not use the .click() method anyway instead of mixing? It's simpler! :)
$('.faq_answer').prev().append(finalRender.cloneNode(true).click(function(){
toggle(this)
}));
Yes, it's possible to use them "together" because jQuery is JavaScript. However in this case there's really no reason to bind event handlers directly like that if you are using the library. It already knows how to manage event handlers, and doing it outside of its control is probably not a good idea unless you really know what you're doing.
I find questions like this are strange, because jQuery is JavaScript.
Based on this mixing up the code that is just plain JavaScript with jQuery code is fine.
But if there is a simpler way of doing what you want in jQuery then I would say to just use jQuery alone.

What is the difference between $(this) and this

I have the following code
$('a').click(function() {
var url= this.href;
alert(url);
});
This works just fine and sure enough the returned result is the url of a tag.
However if I change the above code to
$('a').click(function() {
var url= $(this).href;
alert(url);
});
The result is undefined.
Anyone please help to clear this out for me? I am banging my head for this ....
$(this) creates a jQuery object which wraps this. The native DOM object has an href attribute, but jQuery does not.
$(this).attr("href") would work.
this in your case is the actual dom element, so the anchor tag
$(this) is a jquery object that wraps that dom element with all the jquery goodness.
so .href is not an attribute of that jquery object, but it is of the dom object.
you could use $(this).attr('href') to achieve the same thing using the jQuery object.
This is because you're using a javascript DOMElement in the first example and a jQuery Object in the second example. The jQuery Object wraps around the DOMElement and provides you a lot of features.
You can access the url as follow:
$('a').click(function() { var url= $(this).attr('href'); alert(url); });
The difference is between a DOM element and a jQuery selection.
"this" in the code you've given above is a reference to the link's DOM element. $(this) creates a jQuery selection based upon the DOM element that contains only that link.
The jQuery selection will give you different features at the cost of a little performance. Your link element has a href property (i.e. one you can access through this.href) whereas the jQuery selection has all the normal jQuery properties & methods.
For getting the link target, this.href is definitely the way to go. It is simpler, faster and less verbose.
Lots of good answers, just wanted to add that you could also do this:
$('a').click(function(e) {
alert($(this)[0].href);
});

Categories

Resources