Hiding and Showing Elements with JavaScript or jQuery - javascript

I have an arrow on my site that I'd like if onclick, it hides one element, and shows another. Hitting it again, will hide the element that was shown and show the element that was hidden.
For example, I have
<div id="arrow">▾</div>
<div id="ad"></div>
<div id="description">Hidden</div>
<div id="nav">Also Hidden</div>
So at first, the ad is showing, and then one you've clicked the arrow, I'd like the ad to hide, and then unhide the description and nav.

With jQuery, use .toggle():
$("#arrow").click(function () {
$("#ad, #description, #nav").toggle();
});​
DEMO.
With plain JavaScript, you need to toggle the display property of each element manually:
document.getElementById("arrow").onclick = function () {
var description = document.getElementById("description");
var nav = document.getElementById("nav");
var ad = document.getElementById("ad");
if (ad.style.display == 'none') {
ad.style.display = '';
nav.style.display = 'none';
description.style.display = 'none';
} else {
ad.style.display = 'none';
nav.style.display = '';
description.style.display = '';
}
};​​​​​​
DEMO.

Try this (Since you asked for plain javascript)
window.onload=function(){
var arrow=document.getElementById('arrow').getElementsByTagName('a')[0];
arrow.onclick=function(){
var ad=document.getElementById('ad');
var description=document.getElementById('description');
var nav=document.getElementById('nav');
if(ad.style.display=='none')
{
ad.style.display='block';
description.style.display='none';
nav.style.display='none';
}
else
{
ad.style.display='none';
description.style.display='block';
nav.style.display='block';
}
return false;
};
};
DEMO.​

DEMO
​​ <input id="x" value="x" />
<input id="y" value="y" style="visibility:hidden" />
<input type="button" onclick="toggleBoth()" value="arrow" />​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
.
function toggle(id){
var elem = document.getElementById(id);
if(elem.style.visibility == 'hidden')
elem.style.visibility = 'visible';
else
elem.style.visibility = 'hidden';
}
function toggleBoth()
{
toggle('x');
toggle('y');
}
​

Related

Hide/show, switch between divs using only DOM API

I'm trying to make several divs and switch between them when different buttons are clicked.
Each div will hold something different, for instance the main div is visible on load, the rest are hidden and depending on which button you click you open that div while at the same time hiding the current div. Basically switching between divs smoothly without delay and such.
Below is what I got to, I have 2 divs, the main div is visible from get go, while the other is hidden in my css and when I click on button it displays, but my first div is still visible and I have to click button to make it hidden.
My question is how do I go about making an efficient if statement to make one div appear/visible by clicking a button while the current disappears and joins dosens other that are hidden until I click on their button?
I don't understand JavaScript very well and I want to understand how to do it so no JQuery please :)
And I'm asking about how to do this with divs because I don't know if there is any other way to do it, if there is then please share :)
Thanks
// Div One
var mainDiv = document.getElementById('button');
mainDiv.onclick = function() {
var div = document.getElementById('newpost');
if (div.style.display !== 'none') {
div.style.display = 'none';
} else {
div.style.display = 'block';
}
};
// Div Two
var upgradesDiv = document.getElementById('button2');
upgradesDiv.onclick = function() {
var div = document.getElementById('UpgradesDiv');
if (div.style.display !== 'block') {
div.style.display = 'block';
} else {
div.style.display = 'none';
}
};
I may not fully understand ultimately what you're trying to do. But given your example, you could wrap your div tags in a container and pass some indentifier to your function:
JS
function toggleDiv(target){
var div = document.getElementById('wrapper').getElementsByTagName("div");
if (target == 1) {
div[0].style.display = 'none';
div[1].style.display = 'block';
} else {
div[0].style.display = 'block';
div[1].style.display = 'none';
}
};
HTML
<div id="button" onclick="toggleDiv(0)">one</div>
<div id="button2" onclick="toggleDiv(1)">two</div>
<div id="wrapper">
<div id="newpost"></div>
<div id="UpgradesDiv"></div>
</div>
FIDDLE
Regular; plain-old-javascript way:
function onComplete() {
hide(getById('newPost'));
hide(getById('upgrades'));
clickAndToggle('button1', ['newPost']);
clickAndToggle('button2', ['upgrades']);
}
function clickAndToggle(buttonId, toggleTargetIds) {
var mainDiv = getById(buttonId);
mainDiv.onclick = function() {
toggleTargetIds.forEach(function(targetId) {
toggle(getById(targetId));
});
};
}
function getById(id) {
return document.getElementById(id);
}
function toggle(el) {
window[!isVisible(el) ? 'show' : 'hide'].call(undefined, el);
}
function hide(el) {
el.style.display = 'none';
}
function show(el) {
el.style.display = '';
}
function isVisible(el) {
return el.style.display !== 'none' && el.style.visibility !== 'hidden';
}
document.onreadystatechange = function() {
var state = document.readyState;
if (state == 'complete') {
onComplete();
}
};
<input type="button" id="button1" value="Button #1" />
<input type="button" id="button2" value="Button #2" />
<br />
<div id="newPost">New Post!</div>
<div id="upgrades">Upgrades!</div>
jQuery way
You can use $.hide() and $.show() to toggle visibility.
$(document).ready(function() {
$('#newPost').hide();
$('#upgrades').hide();
clickAndToggle('#button1', ['#newPost']);
clickAndToggle('#button2', ['#upgrades']);
function clickAndToggle(buttonId, toggleTargetIds) {
$(buttonId).click(function() {
$.each(toggleTargetIds, function(idx, targetId) {
//if(!($(targetId).is(":visible"))){$(targetId).show();}else{$(targetId).hide();}
$(targetId).toggle();
});
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="button1" value="Button #1" />
<input type="button" id="button2" value="Button #2" />
<br />
<div id="newPost">New Post!</div>
<div id="upgrades">Upgrades!</div>
To me this seems the most straightforward way of doing this:
var first = 'newpost';
var currentDiv = document.getElementById(first);
function addDivToggle(buttonId, divId)
{
var button = document.getElementById(buttonId);
var newDiv = document.getElementById(divId);
button.addEventListener('click', function(){
currentDiv.style.display = 'none';
newDiv.style.display = '';
currentDiv = newDiv;
});
}
addDivToggle('button1', 'newpost');
addDivToggle('button2', 'UpgradesDiv');
Here i'm assuming that 'newpost' is already visible, and the other divs are hidden.
// The doClick() functions does what onClick() is supposed to do when clicked manually.
// Div One
var mainDiv = document.getElementById('button');
mainDiv.onclick = function() {
var div = document.getElementById('newpost');
if (div.style.display !== 'none') {
div.style.display = 'none';
} else {
div.style.display = 'block';
}
// add this function call
upgradesDiv.doClick();
};
// Div Two
var upgradesDiv = document.getElementById('button2');
upgradesDiv.onclick = function() {
var div = document.getElementById('UpgradesDiv');
if (div.style.display !== 'block') {
div.style.display = 'block';
} else {
div.style.display = 'none';
}
// add this function call
mainDiv.doClick();
};

checkbox oncheck javascript

I have a checkbox That I need to show a div when it is clicked. I have 3 different javascripts that i have attempted to get this to work with.
//function showhide() {
// var checkbox = document.getElementById("assist");
// var expanded1 = document.getElementById("expanded");
// var expanded2 = document.getElementById("expanded2");
// expanded1.style.visibility = (expanded1.style.visibility == 'false') ? "true" : "false";
// alert('test');
//}
function(){
var checkbox = document.getElementById("assist");
var expanded1 = document.getElementById("expanded");
var expanded2 = document.getElementById("expanded2");
checkbox.onchange = function () {
expanded1.style.visibility = this.checked ? 'true' : 'false';
alert('test');
}
//function check() {
// $('chk').click(function () {
// if (this.checked) {
// $("#expanded").show();
// $("#expanded2").show();
// }
// else {
// $("#expanded").hide();
// $("#expanded2").hide();
// }
// });
//}
This is the checkbox below.
<input type="checkbox" runat="server" id="assist" onclick="showhide();" /></div>
The divs that need to be shown/hidden are expanded and expanded2.
I cannot get the javascript functions to be hit from the checkbox could someone tell me what is wrong.
Use the window.onload event to assign the change handler and remove the inline onclick from the HTML. Also the visibility CSS should be visible or hidden.
Fiddle
window.onload = function () {
var checkbox = document.getElementById("assist");
var expanded1 = document.getElementById("expanded");
checkbox.onchange = function () {
expanded1.style.visibility = this.checked ? 'visible' : 'hidden';
};
};
For Hiding the DIV using Jquery you can try below code:
instead of this.checked use $(this).is(':checked')
$('.chk').click( function () {
var $this = $(this);
if( $this.is(':checked') == true ) {
$("#div1").show();
} else {
$("#div1").hide();
}
});
html
<input type="checkbox" runat="server" id="assist" onclick="showhide();" />
<div class="required1" id="mycheckboxdiv1" style="display:none" >
your code;
</div>
this will do for u :)
jquery
<script>
$(document).ready(function() {
$('#mycheckboxdiv1').hide();
$('#assist').click(function(){
if($('#assist').is(':checked')){
$('#mycheckboxdiv1').toggle();
}
else
{
$('#mycheckboxdiv1').hide();
}
});
});
</script>
http://jsfiddle.net/maree_chaudhry/QmXCV/ here is fiddle
You're already using jQuery, so you could just use:
$("#assist").change(function(){
$("#expanded, #expanded2").toggle();
});
jsFiddle here

JavaScript: How can I change the visibility of an element when clicked?

I'm trying to make a code that allows me to make click on any part of the screen and when I click the screen should display the message "click!"
By far I got the next code
html:
<html>
<head>
<title>Sense events anywhere</title>
<script type="text/javascript" src="anywhere.js"></script>
<link type="text/css" rel="stylesheet" href="anywhere.css" />
</head>
<body id="body" onload="init();">
<div id="message"> Click! </div>
</body></html>
JavaScript:
var e;
function init(){
e = document.getElementById("message");
document.getElementById("message").style.visibility = "hidden";
e.onmousedown = displayIt(e);
e.onmouseup = hideIt;
}
function displayIt(e) {
e.style.visibility = "visible";
}
function hideIt() {
e.style.visibility = "hidden";
}
CSS:
body {
}
div#message{
}
By far I only tried to turn the message visible and "invisible" when clicked but it doesn't work
Sorry for my English, I'm not a native speaker. If anyone could help me, that will be great.
Thanks.
var visible = true,
body = document.getElementById("body"),
mess = document.getElementById("message");
body.onclick = function() {
if (visible === true) {
mess.style.visibility = "hidden";
visible = false;
} else {
mess.style.visibility = "visible";
visible = true;
}
}
Edit Replaced body in selector as i didnt notice you wanted any part of the screen clicked
I'd suggest:
function toggleMessage(targetID){
var target = document.getElementById(targetID),
display = target.style.display;
target.style.display = display && display == 'block' ? 'none' : 'block';
}
document.body.addEventListener('click', function(){
toggleMessage('message');
});
Simple JS Fiddle demo.
Amended the above to use visibility (rather than display):
function toggleMessage(targetID){
var target = document.getElementById(targetID),
visibility = target.style.visibility;
target.style.visibility = visibility && visibility == 'visible' ? 'hidden' : 'visible';
}
document.body.addEventListener('click', function(){
toggleMessage('message');
});
Simple JS Fiddle demo.
References:
EventTarget.addEventListener().
Solution with jQuery (I recommend you to use display property. Because, if you use visibility, element will keep its space even it is hidden. With display: none; element is "removed".):
HTML
<div id="message"> Click! </div>
CSS
#message {
display: none;
}
jQuery
$(document).ready(function(){
$(window).click(function(){
$('#message').toggle();
});
});
DEMO: http://jsfiddle.net/j3KVT/2/
If you want to use visibility property then this is (one of many) solution with jQuery:
HTML
<div id="message">Click!</div>
jQuery
$(document).ready(function () {
$('#message').css('visibility', 'hidden');
$(window).click(function () {
if ($('#message').css('visibility') == 'hidden')
$('#message').css('visibility', 'visible');
else $('#message').css('visibility', 'hidden');
});
});
DEMO: http://jsfiddle.net/j3KVT/3/

Javascript to show/hide div of render

Ruby on Rails 3. I am trying to get a button to show or hide a div.
This is not returning any errors but nothing happens.
<input type=button value="Show Archived Postings" onclick="showHide('oldNews');">
<div id="oldNews">
<%= render 'archive_news' %>
</div>
<script language="javascript" type="text/javascript">
function showHide(elementId) {
if (document.getElementById) {
var element = document.getElementById(elementId);
if (element.style.visibility == 'visible') {
element.style.visibility = 'hidden';
} else if (element.style.visibility == 'hidden') {
element.style.visibility = 'visible';
}
}
}
</script>
It will always render my 'archive_news'. What am I doing wrong? Thank you
You can use this code for your requirement. You can use style property for hide and display element when you click on button.
//this would hide when body is loaded
var element = document.getElementById('oldNews');
if(element != null){
element.style.display = 'none';
}
//this would hide when you click on input button
function showHide(elementId) {
var element = document.getElementById(elementId);
if (element != null) {
if(element.style.display != 'none'){
element.style.display = 'none';
}else{
element.style.display = 'block';
}
}
}

Change a div class when a radio option inside it is clicked

This is my first real dive into javascript. I've been going at this for hours and haven't found a solution (though I learned a lot).
<script type="text/javascript">
function changeClass(){
var NAME = document.getElementById("switcher");
var currentClass = NAME.className;
if (currentClass == "switch switch-blue") {
NAME.className = "switch switch-red";
} else {
NAME.className = "switch switch-blue";
}
}
window.onload = function()
{
document.getElementById("switcher").addEventListener( 'click' , changeClass );
}
</script>
Here is the HTML:
<div class="switch switch-blue" id="switcher">
<input type="radio" class="switch-input" name="resp" value="1" id="respyes" checked>
<label for="respyes" class="switch-label">YES</label>
<input type="radio" class="switch-input" name="resp" value="2" id="respno">
<label for="respno" class="switch-label">NO</label>
</div>
The default is a blue background. If they choose no I want it red, then back to blue if they click yes, all that is in the css. If I manually change the class from switch-blue to switch-red, it works. Right now it does absolutely nothing.
Thank you!
Problem here is event propagation when an internal element click event bubbleup so it causing calling your function twice which change class and then revert back so try:
function changeClass(event) {
var NAME = document.getElementById("switcher");
var currentClass = NAME.className;
if (currentClass == "switch switch-blue") {
NAME.className = "switch switch-red";
} else {
NAME.className = "switch switch-blue";
}
if (window.event != undefined) window.event.cancelBubble = true;
event.stopPropagation();
}
window.onload = function () {
document.getElementById("switcher").addEventListener('click', changeClass);
}
event.stopPropagation(); will stop this bubbling and for IE use window.event.cancelBubble = true;
Here is working JSFiddle
Edit
But this will not guarentee the change of class on radio button click as event is bind to parent div so clicking over div anywhere will trigger the event, so try to bind event on the radio-buttons:
Event on Radio click
function changeClass(clickedItem) {
var NAME = document.getElementById("switcher");
var currentClass = NAME.className;
if (clickedItem == 1) {
NAME.className = "switch switch-red";
} else {
NAME.className = "switch switch-blue";
}
}
window.onload = function () {
var yes = document.getElementById('respyes');
var no = document.getElementById('respno');
yes.onclick = function () {
changeClass(2)
};
no.onclick = function () {
changeClass(1)
};
}
function changeClass(elem){
var currentClass = elem.className, blueClass = "switch switch-blue",
redClass= "switch switch-red"
elem.className = (currentClass == blueClass) ? redClass:blueClass;
}
window.onload = function()
{
document.getElementById("switcher").onclick = function(){
changeClass(this);
};
}
JS Fiddle: http://jsfiddle.net/dYt8v/
Looks like it is working fine, when you add the css classes.
Here is a demo. I think you are missing the styles.
Add the style to your head and see if that works for you.
<style>
.switch-blue{
background:blue;
color:#fff;
}
.switch-red{
background:red;
color:#fff;
}</style>
Feel free to change the styles as you need them.
Edit
I just noticed that you have the event listeners attached to the div instead of the radio button. That will change the background when you click the div, instead of the buttons. See this updated fiddle.

Categories

Resources