P
P
pandaa2020-04-30 12:06:33
JavaScript
pandaa, 2020-04-30 12:06:33

Give an example of the most economical code?

The task is very simple, by clicking on the next button, we display the contents of the next section tag, back - of the previous one.

<section>
  <h1>1</h1>
  <button>Next</button>
</section>

<section>
  <h1>2</h1>
  <button>Back</button>
  <button>Next</button>
</section>

<section>
  <h1>3</h1>
  <button>Back</button>
  <button>Next</button>
</section>

<section>
  <h1>4</h1>
  <button>Back</button>
</section>

I want to see the most elegant version.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
R
Rsa97, 2020-04-30
@Rsa97

HTML + CSS only:

A
Alexander Tsymbal, 2020-04-30
@AlexanderTsymbal

On jQuery:
https://codepen.io/tsymbal_su/pen/PoPKXGK
css:

section.active {
  display: block;
}
section:not(.active) {
  display: none;
}

js:
jQuery(document).ready(function($){

  $("section:nth-child(1)").addClass("active");

  $(document).on("click","section.active button",function(){
    if ($(this).text()=="Next") {
      $(this).parents("section").removeClass("active").next("section").addClass("active");
    } else if ($(this).text()=="Back") {
      $(this).parents("section").removeClass("active").prev("section").addClass("active");
    }
  });
  
})

A
Anton Shvets, 2020-04-30
@Xuxicheta

No jquery
https://jsfiddle.net/melchiorio/6sqoherp/
6 lines of js and one wrapper tag

P
pandaa, 2020-04-30
@pandaa

Without changing html

section{
    display: none;
}
.block{
    display: block;
}

let m = document.getElementsByTagName('section');


let i = 0;
let y = 0;

loop(i);

function loop(i){

    m[y].classList.remove('block');
    m[i].classList.add('block');


    let buttons = m[i].getElementsByTagName('button');

    if (buttons.length > 1) {
        if (buttons[0].innerHTML == 'Back') {
            buttons[0].onclick = function () {
                console.log('back');
                y = i;
                i--;
                loop(i);
            }
        }
        if (buttons[1].innerHTML == 'Next') {
            buttons[1].onclick = function () {
                console.log('next');
                y = i;
                i++;
                loop(i);
            }
        }
    }else{
        if (buttons[0].innerHTML == 'Next') {
            buttons[0].onclick = function () {
                console.log('next');
                y = i;
                i++;
                loop(i);
            }
        }
        if (buttons[0].innerHTML == 'Back') {
            buttons[0].onclick = function () {
                console.log('back');
                y = i;
                i--;
                loop(i);
            }   
        }
    }

}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question