Creating JavaScript toggle button



In this video I will show how simple is to make JavaScript toggle button to hide or show an element on HTML document.

Here is the source codes:

<!DOCTYPE html>
<html>
	<head>
		<title>Toggle Button</title>
	</head>
	<body>
		<button onclick="toggle()">Toggle</button>
		<p id="test">Sample Text</p>
		<script>
			var toggled = false;
			function toggle(){
				if(!toggled){
					toggled = true;
					document.getElementById("test").style.display = "none";
					return;
				}
				if(toggled){
					toggled = false;
					document.getElementById("test").style.display = "block";
					return;
				}
			}
		</script>
	</body>
</html>

Here is the live demo of the script:

Sample Text

Or, you can use jQuery to make this toggle thing much easier. Read this tutorial.

loading...