How to make next/previous paragraph visible inside in a div?

Boy Smiley

I have four paragraphs inside a div and the first child (or rather the first paragraph) is visible. Besides, I have two buttons ("next" and "previous") and when the button is clicked I have to hide the current paragraph and show the next/previous paragraph.

I've tried to write a function that accomplishes this goal but it's doesn't seem to be working. It doesn't hide the current paragraph and doesn't show the next/previous sibling.

Here is an example:

var show = function(elem) {
  elem.style.display = 'block';
};

var hide = function(elem) {
  elem.style.display = 'none';
}

var toggle = function(elem, next) {
  if (window.getComputedStyle(elem).display === 'block') {
    hide(elem);
    show(next);
    return;
  }
};

var count = 0;

document.addEventListener('click', function(event) {
  if (!event.target.classList.contains('toggle')) return;

  event.preventDefault();
  var e = document.getElementById("bal");
  var content = e.childNodes[count];
  count++;
  var next = content.nextSibling;
  if (!content) return;

  toggle(content, next);
}, false);
#bal {
  width: 48%;
  border: 1px solid red;
  padding: 1em;
}

#bal p {
  display: none;
}

#bal p:nth-child(1) {
  display: block;
}

#jobb {
  width: 48%;
  float: right;
}
<div id="jobb">
  <form id="gombok">
    <span>
      <input type="button" name="previous" value="Previous">
      <input type="button" class="toggle" href="#bal" name="next" value="Next">
    </span>
  </form>
</div>

<div id="bal" class="sib">
  <p>Paragraph 1</p>
  <p>Paragraph 2</p>
  <p>Paragraph 3</p>
  <p>Paragraph 4</p>
</div>

This function doesn't recognize the current paragraph and if I click two times on the "next" button it deletes the text of the first paragraph.

Aaron3219

@dbramwell has a valuable explanation why your code wasn't working:

  1. Using childNodes rather than children. As you're trying to set style on them, you need to use children to get elements rather than nodes. See here.
  2. if(!content) return;, you need to check if "next" exists, rather than content, as on the last paragraph content will exist when next doesn't

and also corrected your function:

var show = function (elem){
    elem.style.display = 'block';
};

var hide = function (elem){
    elem.style.display = 'none';
}

var toggle = function(elem, next){
    if (window.getComputedStyle(elem).display === 'block'){
        hide(elem);
        show(next);
        return;
    }
};

var count = 0;

document.addEventListener('click', function(event){
    if (!event.target.classList.contains('toggle')) return;
    event.preventDefault();
    var e = document.getElementById("bal");
    var content = e.children[count];
    count++;
    var next = e.children[count];
    if(!next) return;

    toggle(content, next);
}, false);
<!DOCTYPE html>
<html lang="hu">

<head>
    <title>JS példák</title>
    <meta charset="utf-8">
    <meta name="description" content="JavaScript példák">

    <script src="utils.js"></script>
    <script src="./view_para.js"></script>

    <style type="text/css">
        #bal {
            width: 48%;
            border: 1px solid red;
            padding: 1em;
        }

        #bal p {
            display: none;
        }

        #bal p:nth-child(1) {
            display: block;
        }

        #jobb {
            width: 48%;
            float: right;

        }

    </style>



</head>

<body>

    <div id="jobb">
        <form id="gombok">
            <span>
                <input type="button" name="previous" value="Előző">
                <input type="button" class="toggle" href="#bal" name="next" value="Következő">
            </span>
        </form>
    </div>

    <div id="bal" class="sib">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam 
            semper felis in nunc tincidunt lacinia. Aenean interdum,
            lorem pretium maximus euismod, dolor tellus porta velit, sed 
            dapibus ex velit non ante. Morbi consequat rhoncus
            erat, a laoreet felis commodo eget. Phasellus sed justo nibh. 
            Quisque ut felis malesuada, dictum erat vel, vehicula
            nunc. Sed quis facilisis enim. Sed non magna nisl. Duis 
            pellentesque tempus mollis.</p>
        <p>In ultrices mauris risus, ac blandit arcu vehicula vel. Mauris in 
           nulla nulla. Praesent dignissim justo at lorem
            tempus molestie. Nunc interdum, justo non iaculis mollis, quam 
            ipsum mollis massa, id dignissim odio purus quis
            ex. Ut a odio venenatis, malesuada diam et, blandit magna. Nam 
            scelerisque purus ut risus interdum, et vehicula
            augue vestibulum. Proin mattis vehicula arcu, sit amet suscipit 
            velit malesuada sed. In hac habitasse platea
            dictumst. Ut non laoreet dolor. Nunc pellentesque nulla at justo 
            maximus dignissim. </p>
        <p>ellentesque convallis sapien eget tortor fermentum, nec consequat 
           lacus interdum. Sed id pulvinar risus, eu ornare
            tellus. Morbi non ex magna. Nunc sed massa id dolor ultrices 
            consequat. Curabitur fermentum nibh quis sollicitudin
            condimentum. Integer a quam vitae quam fringilla consectetur. 
            Donec vehicula, risus sed sagittis condimentum,
            risus neque luctus mauris, accumsan consectetur lectus nisi id 
            tellus. Quisque eu sapien non lectus imperdiet
            tincidunt consequat non metus. Nulla egestas iaculis arcu sed 
            elementum. Praesent pellentesque sem purus. Nulla
            hendrerit leo lacus, sit amet sodales ante porttitor at. Fusce 
            dapibus laoreet dui, sit amet ornare odio mollis
            non. In hac habitasse platea dictumst. Praesent non ex at nunc 
            ullamcorper interdum. </p>
        <p>Duis tortor leo, ultricies quis placerat vel, scelerisque eu 
           augue. Duis est odio, interdum sit amet ullamcorper
            eget, tincidunt et lectus. Aliquam erat volutpat. Donec tempus 
            porttitor consectetur. Pellentesque ac enim vestibulum,
            eleifend arcu et, hendrerit ligula. Sed quis magna metus. 
            Quisque dignissim metus eget iaculis commodo.</p>
        <p>Interdum et malesuada fames ac ante ipsum primis in faucibus. 
           Vestibulum et est gravida, mattis arcu sed, ultricies
            elit. Sed vitae nisi ac lacus tincidunt varius et eu augue. 
            Etiam ultrices nunc vitae lacinia sagittis. Curabitur
            molestie ac tellus non porttitor. Suspendisse potenti. Praesent 
            facilisis semper iaculis. Sed justo enim, imperdiet
            vitae aliquet id, tempor ut orci. Nunc sed risus arcu. In 
            imperdiet dui eget erat elementum egestas. Pellentesque
            eget urna vitae nulla dapibus euismod. Curabitur nisl diam, 
            pretium id mi posuere, molestie gravida justo. </p>
    </div>

However, this is not the way you should design your code for an easy task like this. I wrote a much simpler function that should do the task equally good.

var count = 0;

function bla() {
  var num = document.querySelectorAll("div#bal p").length - 1;
  if(count < 0) {
  	count = num;
  } else if (count > num) {
  	count = 0;
  }
  
  var all = document.querySelectorAll("div p");
  for (var i = 0; i < all.length; i++) {
    all[i].style.display = "none";
  }
  
  document.querySelectorAll("div p")[count].style.display = "block";
}
div > p {
  display: none;
}

div > p:first-child {
  display: block;
}
<div>
  <p>P1</p>
  <p>P2</p>
  <p>P3</p>
  <p>P4</p>
</div>
<button onclick="bla(count++);">Next</button>
<button onclick="bla(count--);">Previous</button>

Even with your (not shortened) example this is easy to accomplish.

var count = 0;

function bla() {
  var num = document.querySelectorAll("div#bal p").length - 1;
  if (count < 0) {
    count = num;
  } else if (count > num) {
    count = 0;
  }

  var all = document.querySelectorAll("div#bal p");
  for (var i = 0; i < all.length; i++) {
    all[i].style.display = "none";
  }

  document.querySelectorAll("div#bal p")[count].style.display = "block";
}
#bal {
  width: 48%;
  border: 1px solid red;
  padding: 1em;
}

#bal p {
  display: none;
}

#bal p:nth-child(1) {
  display: block;
}

#jobb {
  width: 48%;
  float: right;
}
<div id="jobb">
  <form id="gombok">
    <span>
      <input type="button" onclick="bla(count--)" name="previous" value="Előző">
      <input type="button" onclick="bla(count++)" class="toggle" href="#bal" name="next" value="Következő">
     </span>
  </form>
</div>

<div id="bal" class="sib">
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam semper felis in nunc tincidunt lacinia. Aenean interdum, lorem pretium maximus euismod, dolor tellus porta velit, sed dapibus ex velit non ante. Morbi consequat rhoncus erat, a laoreet felis
    commodo eget. Phasellus sed justo nibh. Quisque ut felis malesuada, dictum erat vel, vehicula nunc. Sed quis facilisis enim. Sed non magna nisl. Duis pellentesque tempus mollis.</p>
  <p>In ultrices mauris risus, ac blandit arcu vehicula vel. Mauris in nulla nulla. Praesent dignissim justo at lorem tempus molestie. Nunc interdum, justo non iaculis mollis, quam ipsum mollis massa, id dignissim odio purus quis ex. Ut a odio venenatis,
    malesuada diam et, blandit magna. Nam scelerisque purus ut risus interdum, et vehicula augue vestibulum. Proin mattis vehicula arcu, sit amet suscipit velit malesuada sed. In hac habitasse platea dictumst. Ut non laoreet dolor. Nunc pellentesque nulla
    at justo maximus dignissim. </p>
  <p>ellentesque convallis sapien eget tortor fermentum, nec consequat lacus interdum. Sed id pulvinar risus, eu ornare tellus. Morbi non ex magna. Nunc sed massa id dolor ultrices consequat. Curabitur fermentum nibh quis sollicitudin condimentum. Integer
    a quam vitae quam fringilla consectetur. Donec vehicula, risus sed sagittis condimentum, risus neque luctus mauris, accumsan consectetur lectus nisi id tellus. Quisque eu sapien non lectus imperdiet tincidunt consequat non metus. Nulla egestas iaculis
    arcu sed elementum. Praesent pellentesque sem purus. Nulla hendrerit leo lacus, sit amet sodales ante porttitor at. Fusce dapibus laoreet dui, sit amet ornare odio mollis non. In hac habitasse platea dictumst. Praesent non ex at nunc ullamcorper interdum.
  </p>
  <p>Duis tortor leo, ultricies quis placerat vel, scelerisque eu augue. Duis est odio, interdum sit amet ullamcorper eget, tincidunt et lectus. Aliquam erat volutpat. Donec tempus porttitor consectetur. Pellentesque ac enim vestibulum, eleifend arcu et,
    hendrerit ligula. Sed quis magna metus. Quisque dignissim metus eget iaculis commodo.</p>
  <p>Interdum et malesuada fames ac ante ipsum primis in faucibus. Vestibulum et est gravida, mattis arcu sed, ultricies elit. Sed vitae nisi ac lacus tincidunt varius et eu augue. Etiam ultrices nunc vitae lacinia sagittis. Curabitur molestie ac tellus
    non porttitor. Suspendisse potenti. Praesent facilisis semper iaculis. Sed justo enim, imperdiet vitae aliquet id, tempor ut orci. Nunc sed risus arcu. In imperdiet dui eget erat elementum egestas. Pellentesque eget urna vitae nulla dapibus euismod.
    Curabitur nisl diam, pretium id mi posuere, molestie gravida justo. </p>
</div>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to make div inside another div visible

How to make words inside a paragraph clickable in flutter?

How to center an absolute paragraph inside a relative div

How to hide paragraph and make visible with heading click using Javascript

Javascript - How to make scrollbar only visible when you move your mouse inside respective div

How to make labels visible inside the pie in openpyxl

How to make a anchor tag clickable which is inside paragraph tag?

How can I add a Paragraph inside a Div dynamically?

How to get content from a paragraph tag inside div via DOMDocument?

How to make a DIV visible and invisible with JavaScript

CSS how to make div visible on focus not working

how to make a div grow to cover a paragraph in javascript with transition?

How to make a "Show more/ Show less" button for a div component? (Not for a paragraph)

How to center paragraph inside another paragraph

how to wrap a paragraph in <div>

How to make a stretchable div with respect to div inside it

how to make div in bottom inside the main div?

Is there a way to make this div visible?

How to make an element visible inside an overlay? HTML & CSS

How to make inside color of cube visible in three.js?

How to hide a text of outside element, but make a text of inside element visible

How to make a widget inside a widget transparent so that the third widget is visible

How to get the text inside a paragraph tag .(div/div/p) using Java(for selenium automation)

Make a paragraph appear inside a picture on picture hover

Unwrap all paragraph tags inside the div jquery

Can't vertically center a paragraph inside a div

center horizontally and vertically paragraph inside div

Adding Vertical Scrollbar in Paragraph inside Div

How will i make the first div visible by default/on pageload?