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

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

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.

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.

fade out on anchor click and fade in href

I would like to know if it is possible to make fadings between two HTML-Documents.
I have a few HTML-Pages but let's make an example with two of them.
index.html, jobs.html
On both I have a menu with <a> buttons. What I want to do is:
I click on Jobs and index.html (which I am currently on) fades out and jobs.html fades in. Something like fading between divs but with a whole HTML document.
Any helps is much appreciated.
Hide the body using css.
Fade in the body
Click a button and grab its ID
Fade out the body
Navigate to the new url
<!DOCTYPE html>
<html>
<head>
<style>
body{
display: none;
}
.myBtn{
cursor: pointer;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script>
$(function(){
$('body').fadeIn();
$('.myBtn').click(function(){
url = $(this).attr('id') + '.html';
$('body').fadeOut(function(){
window.location = url;
});
});
});
</script>
</head>
<body>
<h1>index.html</h1>
<div class="myBtn" id="index">index</div>
<div class="myBtn" id="jobs">jobs</div>
</body>
</html>
http://jsfiddle.net/Dp4Hy/
PS. obviously the fiddle won't work, as you're trying to navigate to a new page, but you can still see the fade in at the beginning, and fade out when you click a button. Just need this script included for all pages to use.
Bottom line, this is not possible without some kind of pre-loading and interaction with a server side component
I would personally recommend PJAX. http://pjax.heroku.com/ It allows you not only catch an event and load a document based on the event, it updates the browser state, url, title, the back button works, etc.
example sites that use it to accomplish similiar behavior
http://bleacherreport.com/articles/1716958-the-top-10-fantasy-qbs-for-2013
http://reciperehab.com/blog/post/the-6-best-salads-for-spring
*disclaimer, I did the second one...
Create your anchor tag and set a javascript onclick event. Call your fadeOut() function (which i've pasted below) You'll want it to fade out when you click, and when the next page loads, you'll want it to fade in:
jsfiddle: http://jsfiddle.net/HmGap/3/
HTML:
<script type="text/javascript">
window.onload=function(){fadeIn('body')};
</script>
<div id="body">
Content <br /><br />
<a onClick="fadeOut('body')" style="cursor:pointer">Click Me to Fade Out</a>
</div>
Javascript:
//fadeEffects
var fade_in_from = 0;
var fade_out_from = 10;
function fadeIn(element){
var target = document.getElementById(element);
target.style.display = "block";
var newSetting = fade_in_from / 10;
target.style.opacity = newSetting;
// opacity ranges from 0 to 1
fade_in_from++;
if(fade_in_from == 10){
target.style.opacity = 1;
clearTimeout(loopTimer);
fade_in_from = 0;
return false;
}
var loopTimer = setTimeout('fadeIn(\''+element+'\')',100);
}
function fadeOut(element){
var target = document.getElementById(element);
var newSetting = fade_out_from / 10;
target.style.opacity = newSetting;
fade_out_from--;
if(fade_out_from == 0){
target.style.opacity = 0;
target.style.display = "none";
clearTimeout(loopTimer);
fade_out_from = 10;
return false;
}
var loopTimer = setTimeout('fadeOut(\''+element+'\')',100);
window.location.href = "link.html";
}
Yes, it's possible, you can append the html in DIV (like you know), or you can use iframes, to manager the fade of the iframe tag

Categories