Reputation: 3829
I have an scenario on which i need to toggle div on link click. But here catch is that we have links with *same class [to click] and same class[to open/toggle]
Toggle is working fine but i need
and vice versa.
Here is JS fiddle link
Some of Code is as below:
$(function () {
$(".textBox").hide();
$('a.clickMe').click(function () {
$(this).nextAll('div.textBox:first').toggle();
});
});
Upvotes: 0
Views: 835
Reputation: 7887
You just have to hide the other divs.
$(function () {
$(".textBox").hide();
$('a.clickMe').click(function () {
var target = $(this).nextAll('div.textBox:first');
$(".textBox").not(target).hide();
target.toggle();
});
});
a{cursor:pointer}
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<a class="clickMe">Toggle my text</a>
<br />
<div class="textBox"> - This text will be toggled</div>
<br /><br /><br />
<a class="clickMe">Toggle my text2</a>
<br />
<div class="textBox"> - This text will be toggled 2</div>
EDIT: Following your comment, here is how you would do using classes.
$(function () {
// you may want to set the hidden class directly in the html
// instead of the line below to avoid the text boxes appearing
// before the js executed the first time.
$(".textBox").addClass("hidden");
$('a.clickMe').click(function () {
var target = $(this).nextAll('div.textBox:first');
$(".textBox").not(target).addClass("hidden");
target.toggleClass("hidden");
});
});
a {
cursor: pointer;
}
.hidden {
display: none;
}
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<a class="clickMe">Toggle my text</a>
<br />
<div class="textBox"> - This text will be toggled</div>
<br /><br /><br />
<a class="clickMe">Toggle my text2</a>
<br />
<div class="textBox"> - This text will be toggled 2</div>
Upvotes: 1
Reputation: 916
http://jsfiddle.net/xe18wusw/6/
$(function () {
$(".textBox").hide();
$('a.clickMe').click(function () {
var thisElem = this;
var isVisibe = $(thisElem).nextAll('div.textBox:first').is(":visible");
$(".textBox").each(function(i,elem){
console.error(thisElem,elem)
if(thisElem!==elem){
$(elem).hide();
}
});
// if()
$(thisElem).nextAll('div.textBox')[isVisibe ? "hide" : "show"]();
$(thisElem).nextAll('.clickMe:first').nextAll("div.textBox").hide();
});
});
Upvotes: 1