Button that Work Conditionally - javascript

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>

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.

Spinning circle on click

I have a code where onclick a word on left side of the page, it shows some text on right hand side of page. Here's the jsfiddle of working code.
Now, my problem is I want to display spinning circle on page on every onclick and then show text on the right hand side of the page. My code for spinning circle is:
HTML:
<div id="loading">
<img src="http://jimpunk.net/Loading/wp-content/uploads/loading1.gif"/>
</div>
JavaScript:
function hideLoading() {
document.getElementById("loading").style.display = 'block';
}
function showLoading() {
document.getElementById("loading").style.visibility = 'visible';
}
CSS:
#loading {
display: none;
}
Now, I don't know how to place them in my working code to get the desired result. Anybody knows the correct way of doing it?
Desired result: onclick "abc" on left hand side, spinning circle should be displayed for 1 sec and then "I should be printed on left side" should be displayed. Again on clicking "mno", first spinning circle should be shown for 1 sec and then text "I should be printed on left side" will be displayed. The fiddle has working version of onclick.
You should use a single handler function on each element that will both hide and show the loading gif. Also, it's a good idea not to use getElementById on every call, so save it in a variable:
<div id="container">
<div id="header">
<h1>Main Title of Web Page</h1>
Here I am trying to split the webpage into two columns and display text.</div>
<div id="one">
<div id="loading">
<img src="http://support.snapfish.com/euf/assets/images/answer_images/SpinningWheel.gif" />
</div>
<div id="message"></div>
</div>
<div id="two"> <b>This is test one<br /></b>
<b>This is test two<br /></b>
</div>
Javascript:
var elements = {};
function loadSpanContent() {
elements.loading.style.display = 'block'; // Show loading gif
spanContent = this.innerHTML
setTimeout(function () {
elements.message.innerHTML = "I should be printed on left side - " + spanContent;
elements.loading.style.display = 'none'; // Hide loading gif
alert("onclick Event detected! " + spanContent);
}, 1000);
}
window.onload = function mydisplayArray() {
var array = ['abc', 'xyz', 'mno'];
elements.loading = document.getElementById("loading");
elements.one = document.getElementById("one");
elements.message = document.getElementById("message");
for (i = 0; i < array.length; i++) {
var span = document.createElement('span');
span.innerHTML = array[i];
span.onclick = loadSpanContent;
one.appendChild(span);
}
};
Here is a fiddle: http://jsfiddle.net/nBaCJ/1/
I'm still confused by what you actually want here, but if you want to have the loading message disappear after one second, you should use setTimeout. Something like this:
function showAlert() {
showLoading();
setTimeout(hideLoading,1000);
//Hide loading circle
var myString = "I should be printed on left side";
document.getElementById("two").innerHTML = myString;
}
But you also need to fix your "showLoading" and "hideLoading". Something like this:
function hideLoading() {
document.getElementById("loading").style.display = 'none';
}
function showLoading() {
document.getElementById("loading").style.display = 'block';
}
http://jsfiddle.net/7uxHC/9/
BTW: if you want your loading gif to appear over your content, then set its position:absolute in css, but note that you gif has a white, rather than transparent background so it will obscure your content.
Your request isn't clear.
But first, you should fix these 2 functions:
function hideLoading() {
document.getElementById("loading").style.display = 'none';
}
function showLoading() {
document.getElementById("loading").style.display = 'block';
}

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.

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.

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