Saturday , February 22 2025

Show and hide block with js

Few examples for showing a block on button click.

Example 1: easy to use

<script type="text/javascript">

function openlink(id){
    display = document.getElementById(id).style.display;

    if(display=='none'){
       document.getElementById(id).style.display='block';
    }else{
       document.getElementById(id).style.display='none';
    }
}
</script>

The block will be opened by clicking on the link:

<a href="#" onclick="openlink('mylink'); return false">Open the link</a>

Content will be shown when you click on the link:

<div id="mylink" style="display: none;">Custom text description </div>

Example 2: the ‘Open’ link will be changed to ‘Close’ when opening the block

Code – link, text block and js to use:

<a id="nepolock" href="javascript:void(0);" onclick="viewdiv('divspoiler');" data-text-show="Close" data-text-hide="Open">Open</a>
<div id="divspoiler" style="display:none;">Custom text description</div>

<script>
    function viewdiv(id) {
        var el = document.getElementById(id);
        var link = document.getElementById('nepolock');
        if (el.style.display == "block") {
            el.style.display = "none";
            link.innerText = link.getAttribute('data-text-hide');
        } else {
            el.style.display = "block";
            link.innerText = link.getAttribute('data-text-show');
        }
    }

</script>

About iryna

I'm Iryna, a web developer from Ukraine with a decade of experience solving complex technical challenges in the world of freelance. Throughout my career, I've worked on everything from troubleshooting server-side issues and optimizing website performance to enhancing user interfaces. On this blog, I share detailed solutions to the technical problems I’ve encountered and methods that have worked best for me. In addition to my technical expertise, I’m also passionate about digital drawing. I hope the tutorials and insights I provide here will help both fellow developers and creatives alike in their own projects.

Check Also

How to open html pages without .html

If your site uses links like http://domain.com/testpage.html and http://domain.com/demo.html, and you want them to open …

Leave a Reply

Your email address will not be published. Required fields are marked *