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 ▼</a>
</div>
<div id="AboutHide" style="display:none">
Hide these details <a href="#" onclick="ShowAbout();">Hide ▲</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:
- change
getElementsById
togetElementById
- change
AbourHide
toAboutHide
- change
b;pck
toblock
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;
}