Home > Software design >  OnClick event to Hide and Toggle Page Section
OnClick event to Hide and Toggle Page Section

Time:11-09

I created two(2) sections.I want to hide a section by default, with a button under it that says “Show More”.

Something like this--- (https://www.livermoretreeremoval.com/tree-service-ulmar) under the "Ulmar Tree Services Top Sights" section.

If the button is clicked, the hidden Section should appear, and the button Text should change to “Show Less”.

If the Button is clicked again, the visible Section should become hidden again, and the Button Text should say “Show More”.

So when hidden, the button says “Show More”, and when visible the button says “Show Less”.

Here’s my JavaScript below:

`

function toggleBlock() {
// get the block
    var myBlock = document.getElementById(‘service-area-two’);

// get the current value of the block’s display property
    var displaySetting = myBlock.style.display;

// also get the block button, so we can change what it says
    var blockButton = document.getElementById(‘Show More’);

// now toggle the block and the button text, depending on current state
    if (displaySetting == ‘block’) {
// block is visible. hide it
    myBlock.style.display = ‘none’;
// change button text
    blockButton.innerHTML = ‘Show Less’;
}
else {
// block is hidden. show it
myBlock.style.display = ‘block’;
// change button text
blockButton.innerHTML = ‘Show More’;
}
}

`

The Section ID: service-area-two The Button Name is: ToggleButton

I know I’m doing a lot of things wrong.

How can I get this button to work?

CodePudding user response:

So as for the button, the show more and show less is not working is what I understood. I think the mistake here is innerHTML. innerHTML means the actual HTML inside the block like for example:

button.innerHTML = '<img src="---'">'

Finally, change innerHTML to innerText.

CodePudding user response:

Use the hidden attribute.
So:

<div hidden id="service-area-two">
    // content
</div>
<button id="Show More" onclick="toggleBlock()">Show more</button>

And the JavaScript logic like this:

function toggleBlock() {
    var myBlock = document.getElementById("service-area-two");

    var blockButton = document.getElementById("Show More");

    if (myBlock.hidden) {
        blockButton.innerHTML = "Show Less";
        myBlock.hidden = false;
    } else {
        blockButton.innerHTML = "Show More";
        myBlock.hidden = true;
    }
}
  • Related