-1

I am working on a little website, which loads the first page but keeps the others hidden until the user clicks the relevant button.

So, when the user clicks "Start Page 2" then the html has an onclick method:

onclick="startPageTwo()"

below is the javascript:

const startPageOne = () => {
    document.getElementById("section-one").style.display = "flex";
    document.getElementById("section-two").style.display = "none";
    document.getElementById("section-three").style.display = "none";
}

const startPageTwo = () => {
    document.getElementById("section-two").style.display = "flex";
    document.getElementById("section-one").style.display = "none";
    document.getElementById("section-three").style.display = "none";
}

const startPageThree = () => {
    document.getElementById("section-three").style.display = "flex";
    document.getElementById("section-one").style.display = "none";
    document.getElementById("section-two").style.display = "none";}

as you can see, there are 3 functions, each doing something slightly different.

How would I go about making a function that checks the id or class of the button pressed, and opens & closes the appropriate page?

Progman
  • 16,827
  • 6
  • 33
  • 48

1 Answers1

0

If your function takes a parameter that represents the selected page, you can add some logic to determine what class should be added to each section in each case:

 const selectPage= (page) => {
    document.getElementById("section-one").style.display = page === 'one' ? "flex" : "none";
    document.getElementById("section-two").style.display = page === 'two' ? "flex" : "none";
    document.getElementById("section-three").style.display = = page === 'three' ? "flex" : "none";
}

Then you could call it differently from each button, e.g:

onclick="selectPage('one')"

leuquim
  • 636
  • 6
  • 16
  • You, sir, are a genius. I thankyou very very much. Your code is clean, I can read and understand it, and your explanation/example is so much better than what I have found in 3 hrs of googling and experimentation. – Andrew Ahn Jul 13 '21 at 16:01