Reputation: 2944
I have this HTML
<li>
<a rel="1" href="/jobwall/job/1">
<img src="http://lcl.moovjob.com/media/images/employers/simonainleydotinfo.jpg">
</a>
</li>
and I have this javascript
$('ul#jobs li a').mouseenter(function(){
$(this).parent().addClass('active');
$.ajax({
type: 'POST',
url: '/jobwall/job_tooltip',
data: 'employer_id='+$(this).attr('rel'),
success:function(html) {
$(this).parent($(this)).addClass('added');
}
});
}).mouseleave(function(){
$('#wrapper').append('Leave');
});
On mouse enter I am wanting to add a class the li that holds the a that has the mouseenter event on it, however I cannot get it to add the class on mouseenter.
Upvotes: 2
Views: 101
Reputation: 5003
Try
$(this).closest('li').addClass('added');
Or just
$(this).parent().addClass('added');
Upvotes: 0
Reputation: 322452
You have two calls to .addClass()
. Which one are you talking about?
The first one should work.
The second one will not because the value of this
has changed inside the success:
callback. You can cache it in a variable and reference it inside.
$('ul#jobs li a').mouseenter(function(){
// cache the parent here, because "this" will have different
// meaning in the callback
var $parent = $(this).parent().addClass('active');
$.ajax({
type: 'POST',
url: '/jobwall/job_tooltip',
data: 'employer_id='+$(this).attr('rel'),
success:function(html) {
// Inside here, "this" no longer references the DOM element
$parent.addClass('added'); // reference the parent you cached
}
});
}).mouseleave(function(){
$('#wrapper').append('Leave');
});
Another option would be to set the context:
property of the AJAX call.
$.ajax({
type: 'POST',
context: this, // set the context to the current "this" for the callback
url: '/jobwall/job_tooltip',
data: 'employer_id='+$(this).attr('rel'),
success:function(html) {
$(this).parent().addClass('added');
}
});
And another option would be to use $.proxy()
to retain the value of this
.
$.ajax({
type: 'POST',
url: '/jobwall/job_tooltip',
data: 'employer_id='+$(this).attr('rel'),
success: $.proxy( function(html) { // Have $.proxy return a function
$(this).parent().addClass('added'); // with the proper "this"
}, this )
});
Upvotes: 2
Reputation: 78667
Your this inside of the success event will be the window not the anchor element. Take a ref of the anchor outside the .ajax call and use it in the success event.
$('ul#jobs li a').mouseenter(function(){
var $this = $(this);
$this.parent().addClass('active');
$.ajax({
type: 'POST',
url: '/jobwall/job_tooltip',
data: 'employer_id='+$(this).attr('rel'),
success:function(html) {
$this.parent().addClass('added');
}
});
}).mouseleave(function(){
$('#wrapper').append('Leave');
});
Upvotes: 1
Reputation: 887225
You're mis-calling the parent
method.
Change it to
$(this).parent()
Upvotes: 0