Friday , December 20 2024

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 admin

Hi there! My name is Iryna, I am a web developer from Ukraine. While working on freelance projects I often face different technical issues and in this blog I publish articles on how to solve them. I am also interested in digital drawing and in this blog you will find brief tutorials that helped me and hopefully can help you as well.

Check Also

Display the date + a few days from the current one

The task in short: you need to make the delivery date + 5 days from …

Leave a Reply

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