Search code examples
javascriptparagraphs

Javascript check if event handler has been clicked


I want to display paragraphs with the help of js, and I want for every time that user clicks button "right" to display a paragraph but instead all of the paragraphs are being showed. How can I check if a user has clicked a button, so that I can display only ONE next paragraph when the button was clicked. Thanx in advance.

<style type="text/css">
p {
    border:1px solid black;
    width:100px;
    height:30px;
    display:none;
}
</style>

<p>some text1</p>
<p>some text2</p>
<p>some text3</p>
<p>some text4</p>
<p>some text5</p>
<input type="button" value = "left"  />
<input type="button" value = "right" 
onclick = "
var p = document.getElementsByTagName('p');
for(var i = 0; i <p.length; i++){ 
show_paragraphs(i);}
" 
id = "right"/>

Solution

  • You need to Itrate over each para and check if the previous para is displayed;if displayed set as display none for the previous and for display block as for current one and return.

    here is the sample code

    <html>
    <style type="text/css">
    p {
        border:1px solid black;
        width:100px;
        height:30px;
        display:none;
    }
    </style>
    
    <p style="display:block">some text1</p>
    <p>some text2</p>
    <p>some text3</p>
    <p>some text4</p>
    <p>some text5</p>
    <input type="button" value = "left"  />
    <input type="button" value = "right" 
    onclick = "navigate()" 
    id = "right"/>
    <script>
    function navigate(){
    var p = document.getElementsByTagName('p');
    for(var i = 1; i <p.length; i++){ 
     if(  p[i-1].style.display == 'block')
      {
        p[i].style.display = 'block' ;
        p[i-1].style.display ='none';
        return;
      }
    }
    }
    </script>
    </html>