Show/Hide Div using JS - javascript

I'm working on a personal website and I'm trying to have a show/hide on click of an image, but I'm not really sure where the problem is.
HTML
<div id="menuopen">
<a href="#" onclick="toggle('menu');">
<img src="assets/Images/menu.gif" alt="Menu">
</a>
</div>
<div id="menu">
<ul>
<li>Home</li>
<li>Home</li>
<li>Home</li>
<li>Home</li>
</ul>
</div>
JS
<script type="text/javascript">
<!--
function toggle(id) {
var item = document.getElementById(id);
if(item.style.display == 'block')
item.style.display = 'none';
else
item.style.display = 'block'; }
//-->
As a side note, this script also did not work using plain text rather than the image, so I don't think that my problem lies there.

Sometimes the style properties are empty/meaningless until they have been set in JavaScript. You can either set the value in JS first or you can have your JS assume the starting state.
Solution 1 - Set state from JS:
var s = document.getElementById('menu').style;
s.display = 'block';
function toggle() {
if(s.display == 'block') { s.display = 'none'; }
else { s.display = 'block'; }
}
Solution 2 - Assume unset means it's visible
function toggle(id) {
var s = document.getElementById('menu').style;
s.display = (s.display!=='block' ? 'block' : 'none');
}

Check this one. Just a short explanation, your function is checking if the element has a block value attached to it's display property which is wrong - by default this property is empty. So, rather ask for none or an empty (default) value.
function toggle(o) {
var e = document.getElementById(o);
e.style.display = (e.style.display != 'none' ? 'none' : '' );
}

I don't have a lot of time to analyze, but I'd recommend using an in-body function with a click trigger instead of pre-defining the function. Something like what's in the fiddle here :
fiddle
Hope this helps, let me know if you want some clarification and I'll do what I can.

Related

JavaScript addEventListener 'click''

I struggling with very basic thing
I am trying to make this side-nav appear and disappear with JavaScript. The code below only activates the nav bar but doesn't deactivate it. Tried all options but I don't know how to call function to close nav-bar.
Thank you
HTML
<div id="mySidenav" class="sidenav">
×
About
Services
Clients
Contact
</div>
<!-- Use any element to open the sidenav -->
<span id="MyElement">×</span>
JS
<script type="text/javascript">
function changeClass() {
document.getElementById("mySidenav").style.width = "250px";
}
window.onload = function() {
document.getElementById("MyElement").addEventListener('click',changeClass);
}
</script>
</body>
</html>
You can't have to objects with the same ID (use name instead?)
You have a typo in else if with comparator mark and another in the next line with assingment mark.
Since in menu.style.width == "-250px" you would be assigning value to -250 (menu.style.width == "0px) would never pass and it would keep assigning value -250 whenever someone clicks the button, but that fails, because you have a typo in your assingment mark.
Width cannot be negative
Is let compatable with your browser?
Have you considered using display:none and display:block (or whatever display you have)?
function toggleMenu() {
var menu = document.getElementById('mySidenav');
if (menu.style.display == "none")
menu.style.display = "inline-block"; //block
else
menu.style.display = "none";
}
window.onload = function() {
document.getElementById("MyElement").onclick = toggleMenu;
}
your else statement section seems to have the comparator (==) and assignment (=) the wrong way around :
} else if (menu.style.width = "250px") {
menu.style.width == "-250px";
}
looks like it should be
} else if (menu.style.width == "250px") {
//setting a negative width will immediately break the toggle logic.
//just set it to 0px.
menu.style.width = "0px";
}
Full example :
function changeClass() {
var sidenavElement = document.getElementById("mySidenav");
if(sidenavElement.style.width == "0px")
{
sidenavElement.style.width = "250px";
}
else
{
sidenavElement.style.width = "0px";
}
}
window.onload = function() {
document.getElementById("MyElement").addEventListener('click',changeClass);
}
#mySidenav
{
overflow:hidden;
height:100px;
background:green;
}
<div id="mySidenav" style="width:0px">
HELLO I AM SIDENAV
</div>
<button id="MyElement">toggle it</button>
There is many problem in your code, you have 2 elements inside your DOM with same ID as mentioned by Marek Maszay.
Your else statement should use == in condition and = for assignation.
Last thing, you should not use width property to display or not an element there is a display property in css
<html>
<body>
<div id="mySidenav" class="sidenav">
<span class="closebtn" id="MyElement">×</span>
<span id="menu">
About
Services
Clients
Contact
</span>
</div>
<!-- Use any element to open the sidenav -->
<span id="MyElement2">×</span>
<script type="text/javascript">
function toggleMenu() {
let menu = document.getElementById('menu');
if (menu.style.display == "") {
menu.style.display = "none";
} else if (menu.style.display == "none") {
menu.style.display = "";
}
}
window.onload = function() {
document.getElementById("MyElement").addEventListener('click',toggleMenu);
}
</script>
...
</body>
</html>
When display value is "", it take the default display value of an element, when its value is none the element is not displayed.
Here is your code modified.
EDIT
For some reason changing width to 0px doesn't hide the element. Element change from line to column, it seem that the browser try to fill element with content and put at least one word per line.
Seem like other people on web are having same problem.

How Do I Get A Div to Completely Clear When I Toggle?

I'm attempting to have a div that runs split screen. The left panel will have multiple links, so the simple toggle I am using is ineffective. I need to be able to clear out the right div and replace it with the next selected link. (Something similar to this
https://www.itriagehealth.com/conditions) Right now, it just stacks the selected links.
I realized I can't do this with CSS alone and am still playing with javascript, but this is the concept I have so far:
https://jsfiddle.net/od9bnez4/1/
function toggle_visibility(id)
{
var e = document.getElementById(id);
if (e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
That fiddle should work, there's just an error in your function declaration, missing the closing brace }, and then change the JavaScript execution (with the gear next to 'JavaScript') to run as a tag in the <head> or <body>, not sure why onLoad isn't working there.
Something like this will do the trick, https://jsfiddle.net/od9bnez4/3/
The heart of it is this,
var left = document.getElementById("left");
var div1 = document.getElementById("div1");
var div2 = document.getElementById("div2");
left.addEventListener('click', function() {
if (div1.style.display == "none") {
div1.style = "display: block;";
div2.style = "display: none;";
} else {
div1.style = "display: none;";
div2.style = "display: block;";
}
});
Obviously this only works for two elements and is very procedural. Typically someone would use something like jQuery for this, or even a framework like Angular or React to build a modularized component.
This is pretty easy. JQuery makes it more flexible.
<!DOCTYPE html>
<html>
<head>
<script>
function toggle()
{
var e = document.getElementById('diva');
var f = document.getElementById('divb');
if (f.style.display == 'none')
{
e.style.display = 'none';
f.style.display = 'block';
}
else
{
f.style.display = 'none';
e.style.display = 'block';
}
}
function togglejquery()
{
if ($('#divb').css('display') == 'none')
{
$('#diva').hide(); // or slideUp('fast');
$('#divb').show(); // or slideDown('fast');
}
else
{
$('#divb').hide();
$('#diva').show();
}
}
</script>
</head>
<body onload="positionScreenBottom();">
<div style="float:left; width:40%;">
<a href='#' onclick='toggle();'>Show A</a><br/>
<a href='#' onclick='toggle();'>Show B</a><br/>
</div>
<div style="float:left; width:60%;">
<div id='diva' style='float:left;'>Here is A</div>
<div id='divb' style='float:left; display:none;'>Here is B</div>
</div>
</body>
</html>

Toggle div by triggering and image click mechanism

I am currently working with the toggle div function. I am using images to be the triggering point for toggling. For example when a div is close an image with a "plus" signs appears to indicate the user to expand and vice versa for compressing the div. The only issue is that I am using two sets of images for expanding and compressing divs but I can only get a set to work but not both. The is example I have doesn't work well in jsfiddle but if you like to look at it there here is the link: http://jsfiddle.net/sQnd9/4/
Here is my example:
<script type="text/javascript">
function toggle1(showHideDiv, switchImgTag) {
var ele = document.getElementById(showHideDiv);
var imageEle = document.getElementById(switchImgTag);
if(ele.style.display == "block") {
ele.style.display = "none";
imageEle.innerHTML = '<img src="images/Plus_Circle.png"/>';
}
else {
ele.style.display = "block";
imageEle.innerHTML = '<img src="images/Minus_Circle.png"/>';
}
}
</script>
<script type="text/javascript">
function toggle2(showHideDiv2, switchImgTag2) {
var ele = document.getElementById(showHideDiv2);
var imageEle = document.getElementById(switchImgTag2);
if(ele.style.display == "block") {
ele.style.display = "none";
imageEle.innerHTML = '<img src=images/arrow_open.png/>';
}
else {
ele.style.display = "block";
imageEle.innerHTML = '<img src=images/arrow_close.png/>';
}
}
</script>
<div><a id="imageDivLink" href="javascript:toggle1('contentDivImg', 'imageDivLink');"><img src="images/Plus_Circle.png";/></a>Example</div>
<br />
<div id="contentDivImg" style="display:none;">
Example1-Content
</div>
<div><a id="imageDivLink2" href="javascript:toggle2('contentDivImg2', 'imageDivLink2');"><img src="images/Plus_Circle.png";/></a>Example2</div>
<br />
<div id="contentDivImg2" style="display:none;">
Example2-Content
</div>
The problem isn't your code (other than the mistakes that #appclay pointed out). The problem is jsfiddle. Just look at the source code it produces. When you put anything in the "javascript" section it's puts it in it's own namespace, preventing access to those function names outside of that block (so your call to toggle1 for example was throwing an undefined function error).
You can see this in action by defining these functions directly as window. properties. Then your code works as expected. See http://jsfiddle.net/sQnd9/7/
In your own code, you presumably would not encapsulate these function names into their own scope, and it would work as expected (but note again that you should make the changes #appclay pointed out).
Also, you probably shouldn't be doing it this way anyway. You should attach the event handlers in the javascript block.
You're missing the quotes on the img src attribute in the second one
You're also referencing the first function in both examples, so the second function never gets called... Try changing:
<div><a id="imageDivLink2" href="javascript:toggle1('contentDivImg2', 'imageDivLink2');"><img src="images/Plus_Circle.png";/></a>Example2</div>
to
<div><a id="imageDivLink2" href="javascript:toggle2('contentDivImg2', 'imageDivLink2');"><img src="images/arrow_open.png" /></a>Example2</div>
Also, I don't know why you have semicolons in your img tags, they shouldn't be there.

Collapsing JavaScript/HTML div on page load?

I need help collapsing a collapsible div on page load.
I'm using this JavaScript code:
<script type="text/javascript">
function switchMenu(obj) {
var el = document.getElementById(obj);
if ( el.style.display != "none" ) {
el.style.display = 'none';
}
else {
el.style.display = '';
}
}
document.getElementById('aboutme').style.display = 'none';
</script>
to collapse HTML div id="aboutme" when the <a ...>about me</a> is clicked:
<div class="container">
about me
<div id="aboutme">
sample text to be expanded and collapsed
</div>
</div>
I can't get the page to close my div#aboutme on page load.
I want this page to load with my div collapsed.
I thought that the JS line
document.getElementById('aboutme').style.display = 'none';
should do the trick but it doesn't. What am I doing wrong?
Thanks for your help.
If you want your div to load collapsed, simply write the following
<div id="aboutme" style="display:none">
sample text to be expanded and collapsed
</div>
This should resolve the problem.
However, if you are still interested in the JavaScript solution keep reading.
As you said I can't get the page to close my div#aboutme on page load - the problem is that you are not using "onload" event.
Simply put the line document.getElementById('aboutme').style.display = 'none'; in your body's onload attribute..
something like this
<body onload="document.getElementById('aboutme').style.display = 'none';">
...
</body>
and you should see the results with JavaScript. I recommend you use "style" method instead. much better.
Exactly how do you make that JS run on window load? It may simply run before the page is rendered
Does clicking on the link work? if it does, that would prove that the issue is simply the loading sequence
The easiest solution would be to place your code at the very end of your HTML file, just before the closing </body> tag. The code below is more generic, and can be placed anywhere. Note that to toggle the link back on I set the display to 'inline' (or block, i.e. whatever it was before - you may want to save that to a variable to be sure)
<script type="text/javascript">
function switchMenu(id) {
var el = document.getElementById(id);
if ( el.style.display != "none" ) {
el.style.display = 'none';
}
else {
el.style.display = 'inline'; //or block - i.e. whatever it is rendered by
}
}
//add to the window onload event
if( window.addEventListener ){
window.addEventListener( 'load', function(){ switchMenu('aboutme')}, false);
} else if (window.attachEvent) {
window.attachEvent("onload", function(){ switchMenu('aboutme') } );
}
</script>

Toggle Visibility (Automatically causing one div element to hide when another is rendered visible)

Essentially what I am trying to do is create a website that has all of its content on the home page but only has some of the content visible at any one time. The way I read to do this is through toggling visibility.
The problem I am having is that: Assume the home page, when you first visit the website is blank (the way I want it to be). Lets say you click on the "about us" link. All of a sudden the about us section becomes visible (the way I want it to be). Now the problem that I have come across is when I know lets say click on the "products" link, I want the "products" content to become visible and the "about us" content to become invisible again. (Essentially creating the illusion of opening a new page within the same page).
Here is the code I have come up with so far. I can make certain div elements visible and invisible (onclick) but I can't figure out how to make sure only one div element is visible at any one time.
<script type="text/javascript">
function toggleVisibility() {
document.getElementById("about").style.display = "";
if(document.getElementById("about").style.visibility == "hidden" ) {
document.getElementById("about").style.visibility = "visible";
}
else {
document.getElementById("about").style.visibility = "hidden";
}
}
</script>
<script type="text/javascript">
function toggleVisibility1() {
document.getElementById("products").style.display = "";
if(document.getElementById("products").style.visibility == "hidden" ) {
document.getElementById("products").style.visibility = "visible";
}
else {
document.getElementById("products").style.visibility = "hidden";
}
}
</script>
The links to make the JavaScript work looks like this:
< href="#" onclick="toggleVisibility();">About
< href="##" onclick="toggleVisibility1();"> Products
here is another, simple function
<script type="text/javascript">
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
</script>
if you click here, #foo will change visibility
<div id="foo">blablabla</div>
Without jQuery, you would want to do something like this:
<style type="text/css">
.content {
display: none;
}
#about {
display: block;
}
</style>
<script type="text/javascript">
function toggleVisibility(selectedTab) {
// Get a list of your content divs
var content = document.getElementsByClassName('content');
// Loop through, hiding non-selected divs, and showing selected div
for(var i=0; i<content.length; i++) {
if(content[i].id == selectedTab) {
content[i].style.display = 'block';
} else {
content[i].style.display = 'none';
}
}
}
</script>
About
Products
<div id="about" class="content">About stuff here</div>
<div id="products" class="content">Product stuff here</div>
Example here: http://jsfiddle.net/frDLX/
jQuery makes this much easier, but if you are beginning with JavaScript, sometimes you want to see the programmatic code, so you can tell what is going on.
This is exactly what jquery makes easier. Take this very simple example of what you're trying to achieve:
<style type="text/css">
.section {
display: none;
}
</style>
<script type="text/javascript">
function toggleVisibility(newSection) {
$(".section").not("#" + newSection).hide();
$("#" + newSection).show();
}
</script>
About
Products
<div id="about" class="section">about section</div>
<div id="products" class="section">products section</div>
Simple solution is like this:
<script type="text/javascript">
function toggleVisibility(divid) {
if (divid="about"){
document.getElementById("about").style.visibility = "visible";
document.getElementById("products").style.visibility = "hidden";
}
else if (divid="products")
{
document.getElementById("products").style.visibility = "visible";
document.getElementById("about").style.visibility = "hidden";
}
}
</script>
< href="#" onclick="toggleVisibility('about');">About
< href="##" onclick="toggleVisibility1('products');"> Products
use CSS display: property
element disappear
document.getElementById("products").style.display = "none";
element appear and is displayed as block (default for div)
document.getElementById("products").style.display = "block";
I posted sample code here: jQuery: menus appear/disappear on click - V2
PS
Here you can find nice examples about differences between display and visibility: http://wiw.org/~frb/css-docs/display/display.html

Categories