JavaScript addEventListener 'click'' - javascript

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.

Related

Javascript : why i have to click 2 times to run the function?

window.onload = function(){
var about2 = document.getElementById("about");
about2.addEventListener("click",about);
}
function about(){
var divabout = document.getElementById("aboutme");
if(divabout.style.display == "none"){
divabout.style.display = "flex";
divabout.style.justifyContent ="center";
}else{
divabout.style.display ="none";
}
}
please tell me the reason why i have to click twice to run this function .And how to fix pls . many thanks .
i just set display:none for 1 div tag in css , and i want to change display attributes .
Because you haven't set any dislplay property to your HTML by default.
That's why On first click javascript sets everything it needs. then started working from 2nd click.
Here is your code, where you dind't add style in html
<div id="about">Hello</div>
<div id="aboutme">About Me</div>
And Here if I fix/add this style="display:flex;justify-content: center;" in your about me like this
<div id="about">Hello</div>
<div id="aboutme" style="display:flex;justify-content: center;">About Me</div>
Now you can check you need only one click to run
window.onload = function() {
var about2 = document.getElementById("about");
about2.addEventListener("click", about);
}
function about() {
var divabout = document.getElementById("aboutme");
if (divabout.style.display == "none") {
divabout.style.display = "flex";
divabout.style.justifyContent = "center";
} else {
divabout.style.display = "none";
}
}
<div id="about">Hello</div>
<div id="aboutme" style="display:flex;justify-content: center;">OK About Me</div>

Button that Work Conditionally

var coll = document.getElementsByClassName("collapsible");
var p;
for (p = 0; p < coll.length; p++) {
coll[p].addEventListener("click", function() {
this.classList.toggle("active");
var content = this.nextElementSibling;
if (content.style.maxHeight){
content.style.maxHeight = null;
} else {
content.style.maxHeight = content.scrollHeight + "px";
}
});
}
<button class="secondaryButton" id="Btn1"
onclick="Funtion();document.getElementById('humble').click()" />1. The Humble Beginning (1908-1944)
<button class="collapsible" id="humble">The Humble Beginning (1908-1944)
</button>
<div class="content" id="humble2">
<div>content</div>
I use the code above to create a button that trigger the collapsible content to open. How can I make the button only work when the content is collapsed but not when it is open?
The simplest concept is, once your button is clicked, always check to see if the target is already open, if so, then return. Since there's error-prone and incomplete code above, below is an attempt to straighten things out.
<html>
<head>
<script>
function toggleContent(o) {
var contents = document.querySelectorAll(".collapsible .content");
for (var i=0; i<contents.length; i++) {
contents[i].style.display = 'none';
}
document.getElementById(o.dataset.target).style.display = 'block';
}
</script>
</head>
<body>
<div class="collapsible">
<button data-target="humble1" onclick="toggleContent(this)">1. The Humble Beginning (1908-1944)</button>
<button data-target="humble2" onclick="toggleContent(this)">2. The Humble Middle (1908-1944)</button>
<button data-target="humble3" onclick="toggleContent(this)">3. The Humble Ending (1908-1944)</button>
<div class="content" id="humble1">content 1</div>
<div class="content" id="humble2" style="display:none">content 2</div>
<div class="content" id="humble3" style="display:none">content 3</div>
</div>
</body>
</html>
Basically, when each button is clicked, all content blocks are hidden, with the target remaining open.
This approach is closer to your existing code. Perhaps it gives you some more insight in what actually happens in your code.
it's all up to you :)
1st:
Your humble2 div is broken in the HTML because it does not have a closing tag.
Fix this first.
2nd:
The best practise is not to change the content height through JS but use classes that represent the collapsed or expanded status.
.collapsed {
height:0;
}
Now you can ask for the status of the content div.
if (content.classList.contains('collapsed') == 1){
content.classList.add('collapsed');
} else {
content.classList.remove('collapsed');
}
note 1:
I'd go for height instead of maxHeight to prevent other strange behavior later.
Only use maxHeight if you have a good reason.
note 2:
give your content div an ID for easier selection instead of using this.nextElementSilbling.
At the moment you can never change something on your HTML DOM without making your code fail because the next silbling has changed.
note 3:
If you want to stay with the height concept:
Your if (content.style.maxHeight) {} will allways return true because it returns a string that is never empty.
Even if the maxHeight is 0 pixels it will return '0px' which is not an empty string and tho true.
But you already figured out that this is not working as intended. So you set the maxHeight to null which results in false.
better do this:
(content.style.maxHeight == '0px') {...}
and:
content.style.maxHeight = '0px';
This way you allways use the string type and prevent unintended behavior.
here you canf ind more about the Truthly and falsy concept in javascript:
Truthy and falsy in JavaScript
I don't know what the question is. But I think this is what you want.
function a() {
var div = document.getElementById("div");
var button = document.getElementById("button");
if (div.style.visibility == "visible") {
div.style.visibility = "hidden";
button.innerHTML ="Open";
}
else {
div.style.visibility = "visible";
button.innerHTML ="Close";
}
}
<div id="div" style="visibility: hidden;">
Some content
</div>
<button onclick="a();" id="button">Open</button>

How can I make the height of a div bigger onclick of a button and then change back to it's original height when click again?

I have a div id="coding" set on height:300px on CSS.
when I click another div id="menu", I want #coding to change it's height to 800px. I managed to do that like this
<script>
function changec() {
document.getElementById('coding').style.height = "800px";
}
</script>
Now, when click the #menu again, I want the height to get back to it's original 300px value. Can someone help? The code is:
HTML
<div id="coding">
<div id="menu" onclick="changec()">≡</div>
...
</div>
CSS
#coding{
...
height:300px;
}
Simple check if the value is set - remove it (then CSS height will take over).
function changec() {
var xDiv = document.getElementById('coding');
if (xDiv.style.height == '')
xDiv.style.height = '800px'
else
xDiv.style.height = ''
}
Demo: http://jsfiddle.net/ygalanter/BLE6N/
one of the solution for your problem is as follows:
First count how many times you click on #menu
now depending on your expectation you can change the javascript as follows
<script type="text/javascript">
var count = 0;
function changec() {
count++;
if(count%2==1)
document.getElementById("coding").style.height = "800px";
else
document.getElementById("coding").style.height = "300px";
}
</script>
Another alternative solution is
<script type="text/javascript">
function changec() {
var currentheight = document.getElementById('coding').clientHeight;
if (currentheight == 300)
document.getElementById('coding').style.height = "800px";
else if (currentheight == 800)
document.getElementById('coding').style.height = "300px";
}
</script>
Not sure why you tagged jQuery since you didn't use it, but still...Considering the possibility that you are willing to use/learn it, I created a jsFiddle for it: http://jsfiddle.net/Tm2Hd/.
CSS:
#coding{
border:1px solid black; /*optional: Keep track of your div's expand*/
height:300px;
}
#coding.larger{
height:800px;
}
JS:
function changeHeight() {
if($('#coding.larger').length>0)
{
$('#coding').removeClass("larger");
}
else
{
$('#coding').addClass("larger");
}
}
HTML
<div id="coding">
<!--<div onclick="changeHeight()">≡</div>
Personally, I don't suggest using divs as clickable objects... Why don't you use buttons instead?
-->
<button onclick="changeHeight()">≡</button>
...
</div>
My solution to your problem is: Create a new class named larger, pointing to your div, and toggle between this and the original whenever you click the button.

JS source to show/hide divs, didn't work as I expected

I am writing the source code to show/hide divs. If I try to show a new div, however, it is hidden behind the currently shown div.
Here is what I built: http://talkbox.co.il/text.htm
If you try to show 'options' and then 'notific' (or vice versa), you will see that it sometimes doesn't work so well. You will need to click twice for it to work. Why isn't it working so well?
I think maybe the update of this.isMenuOptionsOpen = false; this.isMenuNotificOpen = false; is causing it. How can I fix this?
This is the full source:
<script>
this.isMenuOptionsOpen = false;
this.isMenuNotificOpen = false;
function menuOptions() {
if (this.isMenuOptionsOpen == false) {
document.getElementById('menuOptions').style.display = 'block';
this.isMenuOptionsOpen = true;
document.getElementById('menuNotific').style.display = 'none'; // close another menu if open
}
else {
document.getElementById('menuOptions').style.display = 'none';
this.isMenuOptionsOpen = false;
}
}
function menuNotific() {
if (this.isMenuNotificOpen == false) {
document.getElementById('menuNotific').style.display = 'block';
this.isMenuNotificOpen = true;
document.getElementById('menuOptions').style.display = 'none'; // close another menu if open
}
else {
document.getElementById('menuNotific').style.display = 'none';
this.isMenuNotificOpen = false;
}
}
</script>
<!-- buttons to show/hode the divs-->
options <br>
notific
<!-- end buttons to show/hode the divs -->
<!-- divs to show/hide -->
<div id='menuOptions' style='width:100px; height:100px; background-color:green; display:none; position:relative; color:black;'>menu options</div>
<div id='menuNotific' style='width:100px; height:100px; background-color:yellow; display:none; position:relative; color:black;'>menu notific</div>
<!-- end divs to show/hide -->
When you open Options then Notific, isMenuOptionsOpen is still set to TRUE, so when you ask to open it, your function try to close it and set isMenuOptionsOpen to FALSE, and finaly a second click open it.
You need to set isMenuOptionsOpen to FALSE when you open Notific.

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