Home > Mobile >  Using an anchor to show/hide divs in an asp mvc app
Using an anchor to show/hide divs in an asp mvc app

Time:10-15

In my Asp MVC program I can toggle a div with a button. cshtml:

<button onclick="ShowPubs()"> Click to show or hide</button>

JScipt:

function ShowPubs() {

var x = document.getElementById("myPubs");

if (x.style.display === "none") {

    x.style.display = "block";

} else {

    x.style.display = "none";

}

}

and this works fine,

however, when trying to use links as in this code: cshtnl:

<div id="AboutShow" style="display:block">
   Show the hidden piece <a href="#" onclick="ShowAbout();">Show &#9660;</a>

  </div>

  <div id="AboutHide" style="display:none">
   Hide these details <a href="#" onclick="ShowAbout();">Hide &#9650;</a>

   A lot more stuff

  </div>

using this JavaScript:

function ShowAbout() {

var x = document.getElementById("AboutShow");

var y = document.getElementsById("AbourHide");

if (x.style.display === "none") {

    x.style.display = "block";

    y.style.display = "none";

} else {

    x.style.display = "none";

    y.style.display = "b;pck";

}

return false;

}

The page url adds the # to the url and nothing else happens, what am I doing wrong here, please?

CodePudding user response:

In else you use y.style.display="b;pck" which is not correct way. it must be block;

You need something like this.

  <!DOCTYPE html>
    <html>
    <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
    #myDIV {
      width: 100%;
      padding: 50px 0;
      text-align: center;
      background-color: lightblue;
      margin-top: 20px;
    }
    </style>
    </head>
    <body>



    <a href="#" onclick="myFunction()">Try it</a>

    <div id="myDIV">
    This is my DIV element.
    </div>


    <script>
    function myFunction() {
      var x = document.getElementById("myDIV");
      if (x.style.display === "none") {
        x.style.display = "block";
      } else {
        x.style.display = "none";
      }
    }
    </script>

    </body>
    </html>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Let me know if this works for you

CodePudding user response:

  1. change getElementsById to getElementById
  2. change AbourHide to AboutHide
  3. change b;pck to block

Code:

function ShowAbout() {

            var x = document.getElementById("AboutShow");

            var y = document.getElementById("AboutHide");

            if (x.style.display === "none") {

                x.style.display = "block";

                y.style.display = "none";

            } else {

                x.style.display = "none";

                y.style.display = "block";

            }

            return false;
        }

result: enter image description here

  • Related