Reputation: 13
I have got this code:
<head>
<link rel="stylesheet" href="style.css" type="text/css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<script type="text/javascript">
function toggleDiv(divId) {
$("#"+divId).toggle();
}
</script>
<a href="javascript:toggleDiv('myContent');">Show comments</a><br>
<div id="myContent">
My text1
</div>
<a href="javascript:toggleDiv('myContent');">Show comments</a><br>
<div id="myContent">
My text2
</div>
<a href="javascript:toggleDiv('myContent');">Show comments</a><br>
<div id="myContent">
My text3
</div>
My style.css code:
#myContent {
display: none;
}
I want that, when I click on first Show comments, that to show first text (My text1), then I click on second Show comments, that to show second text (My text2), then I click on third Show comments, that to how third text (My text3). And such a code is a lot.
How to do, that don't be: Click on second Show comments don't show me first text, but show me second text? How to adapt?
Upvotes: 0
Views: 87
Reputation: 174
use Prev or Next jquery:
<a class="showMessage">Show comments</a>
<div class="myContent">
My text1
</div><br><br>
<a class="showMessage">Show comments</a>
<div class="myContent">
My text2
</div><br><br>
<a class="showMessage">Show comments</a>
<div class="myContent">
My text3
</div>
$(".showMessage").click(function(ev){
$(this).next().toggle();
})
example: https://jsfiddle.net/zm3Lg85a/?utm_source=website&utm_medium=embed&utm_campaign=zm3Lg85a
Upvotes: 1
Reputation: 721
Ids must be uniques:
<a href="javascript:toggleDiv('myContent1');">Show comments</a><br>
<div id="myContent1">
My text1
</div>
<a href="javascript:toggleDiv('myContent2');">Show comments</a><br>
<div id="myContent2">
My text2
</div>
<a href="javascript:toggleDiv('myContent3');">Show comments</a><br>
<div id="myContent3">
My text3
</div>
By the way, it's better to use click event. <a onclick="toggleDiv('anId')">Show comments</a>
You can go with something else:
<div>
<a onclick="toggle(this);">Show comments</a><br>
<div>
My text1
</div>
</div>
<div>
<a onclick="toggle(this);">Show comments</a><br>
<div>
My text2
</div>
</div>
<div>
<a onclick="toggle(this);">Show comments</a><br>
<div>
My text3
</div>
</div>
And the javascript toggle function could use jquery:
function toggle(element){
$(element).parent().find('div').toggle();
}
Something like that would be easier to maintain. Not tested.
Upvotes: 0