Reputation: 1215
HTML:
<div id="p1">
<a href="javascript:void(0)">p1</a>
<p "style=display:none;">hi</p>
</div>
<div id="p2">
<a href="javascript:void(0)">p1</a>
<p "style=display:none;">welcome</p>
</div>
Script:
$("#p1").click(function () {
$("#p1 p").toggle();
});
$("#p2").click(function () {
$("#p2 p").toggle();
});
In this when i click p1 it is showing its contents and similary p2. What I need is to display only the clicked contents description the other needs to be hide.How can i do this.
Upvotes: 1
Views: 145
Reputation: 4421
You need extra check on click.
$("#p1").click(function () {
$("#p1 p").toggle();
if ($("#p2 p").is(':visible')) {
$("#p2 p").toggle();
}
});
$("#p2").click(function () {
$("#p2 p").toggle();
if ($("#p1 p").is(':visible')) {
$("#p1 p").toggle();
}
});
Upvotes: 1
Reputation: 5291
Please see this demo
$("#p1").click(function () {
$("p").each(function() {
if ($(this).parent("a").attr("id") !== "p1") {
$(this).hide();
}
});
$("#p1 p").toggle();
});
$("#p2").click(function () {
$("p").each(function() {
if ($(this).parent("a").attr("id") !== "p2") {
$(this).hide();
}
});
$("#p2 p").toggle();
});
Upvotes: 2
Reputation: 388316
I may do it like
<div class="item">
<a class="header" href="#">p1
<p style="display:none;">hi</p>
</a>
</div>
<div class="item">
<a class="header" href="#">p2
<p style="display:none;">hi</p>
</a>
</div>
and
var $ps = $('.item p')
$(".item a").click(function (e) {
var $this = $(this), $p = $this.children('p');
$ps.not($p).hide();
$p.toggle();
e.preventDefault();
});
Demo: Fiddle
Upvotes: 1
Reputation: 4273
$("#p1").click(function () {
$("#p1 p").css('display','');
$("#p2 p").css('display','none');
});
$("#p2").click(function () {
$("#p2 p").css('display','');
$("#p1 p").css('display','none');
});
Here is fiddle
Upvotes: 1
Reputation: 57105
$("#p1").click(function () {
$('#p2 p').hide();
$("#p1 p").toggle();
});
$("#p2").click(function () {
$('#p1 p').hide();
$("#p2 p").toggle();
});
Upvotes: 1
Reputation: 337560
For blocks of code with common logic, you should definitely try to genericise your code. With that in mind, use classes instead of ids, and try this:
<div id="p1" class="content-toggle">
<a href="javascript:void(0)">p1</a>
<p style="display:none;">hi</p>
</div>
<div id="p2" class="content-toggle">
<a href="javascript:void(0)">p1</a>
<p style="display:none;">welcome</p>
</div>
$('.content-toggle').click(function() {
$('.content-toggle p').hide();
$('p', this).show();
});
Note, you also had the "
in the wrong place on the style
attribute of your HTML.
Upvotes: 3
Reputation: 3272
You could do something like below
$("#p1").click(function () {
$("#p2 p").hide();
$("#p1 p").toggle();
});
$("#p2").click(function () {
$("#p1 p").hide();
$("#p2 p").toggle();
});
Upvotes: 1