Reputation: 33
I've got a little problem, which is onclick function fails to make simultaneously two different changes to html document. What's needed is - click on link should toggle "active" class of parent element and toggle visibility of respective hidden div. What I've got is changes are made alternately with each successive click (I provided jsfiddle link below). Worked fine until I added closest() (or parent()) function. I have no idea what's going on. Would appreciate some help.
Here is html:
<div id="wrapper">
<div class="argle"><a href="#">Argle</a>
</div>
<div class="bargle"><a href="#">Bargle</a>
</div>
<div class="shmargle"><a href="#">Schmargle</a>
</div>
</div>
<div id="windows">
<div class="w-argle">Lorem ipsum dolor sit amet, consectetuer adipiscing elit,</div>
<div class="w-bargle">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam er</div>
<div class="w-shmargle">Lorem ipsum dolor sit amet, consectetuer adipiscing elit,.</div>
</div>
Here is js:
$(function () {
$('#wrapper a').click(function (event) {
event.preventDefault();
var parentElement = $(this).closest('div');
var targetElement = $('.w-' + parentElement.attr('class'));
parentElement.toggleClass('active');
targetElement.toggle();
});
});
Online here: http://jsfiddle.net/alalpgrlv/ycJk4/4/
Upvotes: 3
Views: 768
Reputation: 1
the problem appears, because you add the class active to the parentElement. ( that means the second time, you are searching for an in-existent element ).
You can try to get only the first class
parentElement.attr('class').split(" "))[0];
or you can simple add the targetElement class using HTML5 data on the element.
I modified your example, here is the link:
Upvotes: 0
Reputation: 7380
You want like this DEMO http://jsfiddle.net/yeyene/ycJk4/6/
$(function () {
$('#wrapper a').click(function (event) {
$('#windows div').slideUp();
$('#windows .w-'+$(this).parent('div').attr('class')).slideToggle(500);
});
});
Upvotes: 0
Reputation: 3912
$(".argle").click(function(){
$("#windows").find('.w-argle').slideToggle();
});
http://jsfiddle.net/ablealias/zCFff/1/
Upvotes: 1
Reputation: 1427
You add "active" class to the element, and then you use it as a part of selector in targetElement so targetElement will be i.e.: $('.w-argle active') which not exists. Try this.
cls = (parentElement.attr('class').split(" "))[0];
var targetElement = $('.w-' + cls);
Upvotes: 1
Reputation: 14025
Working example : DEMO
$(function () {
$('#wrapper a').click(function (event) {
event.preventDefault();
var parentElement = $(this).closest('div');
var targetElement = $('.w-' + parentElement.attr('class'));
//Hide all other div
$('[class^=w-]').not(targetElement).hide();
//Remove active class
$('#wrapper').find('div').not(parentElement).removeClass('active');
//Toggle clicked link
parentElement.toggleClass('active');
targetElement.toggle();
});
});
Upvotes: 1