Reputation: 345
I was wondering how to use the $(this) selector in a function. I have tried multiple ways found on the internet but none seem to work.
Here's an example of what I'm trying to do
function bobsCar() {
$(this).toggle();
}
$('p').click(function() {
bobsCar();
});
Upvotes: 0
Views: 1284
Reputation: 1
In JavaScript the $(this) is a context-pointer. It gives you the top-most context that is placed on the stack.
function bobsCar(elm) { console.log(elm);
$(elm).parent().toggleClass(); }$('p').click(function() { var $this=$(this); bobsCar($this); });
jsfiddle.net/q325d6zw
Upvotes: -1
Reputation: 944114
The value of this
inside the click event handler is not a string representation of a selector. It is a DOM node.
If you want to override the normal value of this
for a function, you can specify it with call
or apply
.
bobsCar.call(this);
You could pass it as an argument instead.
bobsCar(this);
function bobsCar(domNode) {
$(domNode).toggle();
}
You should probably just use the function as the event handler in the first place though.
$('p').click(bobsCar);
Upvotes: 1
Reputation: 66425
function bobsCar() {
$(this).toggle();
}
jQuery('p').click(function() {
bobsCar.call(this);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>click me</p>
You need to understand JavaScript contexts. By default if you call a method inside your click callback, it will use the global context (in this case window
- try console logging this
in your broken function), not the one in the callback. You can use call
or apply
to specify the context (in this case this
refers to the DOMNode element in the callback, so we pass the same context to the function and it works).
This is a good article on the topic: http://yehudakatz.com/2011/08/11/understanding-JavaScript-function-invocation-and-this/
Upvotes: 1
Reputation: 388416
Another option is to execute the function with a custom context like.
function bobsCar() {
$(this).toggle();
}
$('p').click(function() {
bobsCar.call(this);
});
In your case since you are calling bobsCar
without a context, this
inside it refers to the window
object that is why it is not working.
Upvotes: 1
Reputation: 7490
This inside the function no longer reefers tot he 'p' tag, you could pass it
function bobsCar(el) {
el.toggle();
}
$('p').click(function() {
bobsCar($(this));
});
Upvotes: 0
Reputation: 18600
You cannot directly use this
in called function. You must have to pass selected object as function argument.
function bobsCar(element) {
$(element).toggle();
}
$('p').click(function() {
bobsCar(this);
});
Upvotes: 0