Deimantas Deimantas - 3 months ago 8
HTML Question

How to do with javascript, that when click on href, it's show text?

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?

Answer

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