Reputation: 2186
I am trying to toggle classes using jQuery and I'm struggling to do so. I have my HTML structure & jQuery as below
<div class="mainFacet bmargin5">
<div class="head line">
<div class="facet-title" title="Click to collapse">
<h2 class="unit-line">Processor</h2>
<span class="icon minus"></span>
</div>
</div>
<ul style="display:inline-block">
<li>i3</li>
<li>i5</li>
<li>i7</li>
</ul>
</div>
jQuery
$('.facet-title').click(function () {
$(this).parent().parent().children("ul").slideToggle();
$(this).attr("title", ($(this).attr("title") == "Click to Collapse") ? "Click to Expand" : "Click to Collapse");
$(this).toggle(function () {
$(this).children("span").removeClass("minus").addClass("plus");
}, function () {
$(this).children("span").removeClass("plus").addClass("minus");
});
});
So its simple. I want three thing to happen on facet-title click.
Here is a demo to show my progress with the first 2 tasks...
Upvotes: 0
Views: 1371
Reputation: 257
you are losing your reference to this
in closures. Do the following:
var that = $(this);
$(this).toggle(function () {
$(that).children("span").removeClass("minus").addClass("plus");
}, function () {
$(that).children("span").removeClass("plus").addClass("minus");
});
EDIT: To explain for future readers: this
, unlike variables, changes the object it references within a closure. So, in order to preserve the reference to the calling object (.facet-title
in the case above), you need to assign it to a variable. This variable then can be used inside the closure.
Upvotes: 1
Reputation: 82231
You can use:
$(this).closest('.mainFacet').find('span').toggleClass("minus plus");
Upvotes: 1
Reputation: 22488
You can do it this way:
$('.facet-title').click(function () {
var self = $(this); // create a variable to reference .facet-title
$('span', self).toggleClass('minus plus'); // toggle plus/minus classes
$(this).parent().siblings("ul").slideToggle(function() {
var title;
// Use self instead of $(this) which would refer to the ul
self.attr('title') == 'Click to collapse' ? title = 'Click to expand' : title = 'Click to collapse';
self.attr('title', title);
});
});
Upvotes: 1