I have this simple function which toggles a hidden element in the webpage.
function showtable(id)
{
if(document.getElementById(id).style.display == 'block')
{
document.getElementById(id).style.display = 'none';
}else{
document.getElementById(id).style.display = 'block';
}
}
<input type="button" value="Toggle" onclick="showtable('id');" />
This works fine, but I want to toggle off some other (table) element (with certain ids) (except for the one which is being toggled, whether on or off) on the page every time the button is clicked.
You could use jQuery, but if you don't want to use that; here is a pure javascript example. To see how it works, copy paste it in a text file, save it as test.htm and open it in a browser. It contains three tables, each with a button above it. When clicking a button, it's table gets displayed and all other tables get hidden. If you need more tables, give them an id, and add their id to the array in the function:
var ids = ["redTable", "greenTable", "blackTable", "anotherTable"];
If you want to be able to toggle that table also, it will off course also need a button:
<input type="button" value="Toggle Green Table" onclick="showtable('anotherTable');" />
example:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function showtable(id) {
var ids = ["redTable", "greenTable", "blackTable"];
for(var i = 0; i < ids.length; i++) {
if(ids[i] != id)
document.getElementById(ids[i]).style.display = "none";
}
document.getElementById(id).style.display = "block";
}
</script>
</head>
<body>
<input type="button" value="Toggle Red Table" onclick="showtable('redTable');" /><br />
<table style="width: 100px; height: 100px; background-color: red;" id="redTable">
<tr>
<td>redTable</td>
</tr>
</table>
<input type="button" value="Toggle Green Table" onclick="showtable('greenTable');" /><br />
<table style="width: 100px; height: 100px; background-color: green; display: none;" id="greenTable">
<tr>
<td>greenTable</td>
</tr>
</table>
<input type="button" value="Toggle Black Table" onclick="showtable('blackTable');" /><br />
<table style="width: 100px; height: 100px; background-color: black; display: none;" id="blackTable">
<tr>
<td>blackTable</td>
</tr>
</table>
</body>
</html>
You could select all the other DOM elements, set their display attribute to "none", and then only show the one that should be visible.
Another way would be to keep track of the visible element in a variable:
var visibleElement = null;
When you toggle an element, you make that one the visible element and hide the previously visible one:
// Hide the previously visible element, if any.
if (visibleElement != null)
{
visibleElement.style.display = 'none';
}
// Make your new element the visible one.
visibleElement = document.getElementById(id)
visibleElement.style.display = 'block';
Easy using jQuery. For example, give each toggled element a class like toggle_element and then in JS:
$('.toggle_element').hide();
$('#id').show();
This will hide all elements with class toggle_element and show element with id id.
JSFiddle example here.
Related
I have built a little filter application with a widget. Now I have some filter tags which show you what kind of filter options you have chosen. Now If there is no filter selected the tags must be hidden. I figured out how to do that with a javascript function. The css empty rule does not work with the widget.
But I cannot figure out how to make them visible again.
let divs = document.getElementsByClassName('display');
for (let x = 0; x < divs.length; x++) {
let div = divs[x];
let content = div.innerText.trim();
console.log("Trim Test" + content);
if (content == '') {
div.style.display = 'none';
}
else{
div.style.display = 'inline';
}
}
<div class="tags123">
<span id="display" class="display"> <p id="display1" class="display1"></p></span>
<span id="display" class="display"> <p id="display3" class="display3"></p></span>
<span id="display" class="display"> <p id="display2" class="display2"></p></span>
</div>
The if condition works, my tags are hidden. But the else condition does not seem to trigger If I enter something in the Tags.
I have attached two pictures to show the if condition is working. Do I have to enclose it with some event listener ? Thank you for your time.
It's not quite clear to me how your widget interacts with your markup, but a simple way to toggle the visibility of empty elements would be to filter out the ones with content and use a class that gets toggled on click, like so:
const btn = document.getElementById('btn');
const items = document.getElementsByClassName('foo');
btn.onclick = () => [...items]
.filter(i => !i.textContent)
.forEach(i => i.classList.toggle('hidden'));
.foo::after {
content: 'x';
border-radius: 50%;
background-color: grey;
}
.foo.hidden {
display: none;
}
<button id="btn">toggle visibilty</button>
<div>
<span class="foo">Text</span>
<span class="foo"></span>
<span class="foo"></span>
</div>
I am new to JavaScript. I created this code in order to try and make buttons that will hide
and show certain pictures on the page. I have 3 buttons, the first of which is supposed to run my JavaScript code in <script></script> tags, the other two just have Javascript code inside them and they work fine. But they don't hide the picture once they are clicked a second time, which is why I am trying to do that for the first one if possible.
For some reason, I cannot get the first button with "open()" to work the way I want with my Javascript code. Can anyone with more experience please explain to me what I am doing wrong? Thank you in advance...
var btn1 = document.getElementById('1');
var btn2 = document.getElementById('2');
var btn3 = document.getElementById('3');
var display1 = btn1.getAttribute('display')
var display2 = btn2.getAttribute('display')
var display3 = btn3.getAttribute('display')
function open() {
if (display1 === ('none')) {
btn1.setAttribute('display', 'block');
} else {
btn1.setAttribute('display', 'none');
}
}
<img id="1" src="forge.PNG" style="height:320px; display:none; padding:10px">
<img id="2" src="lizard.jpg" style="height:320px; display:none; padding:10px">
<img id="3" src="walkway.jpg" style="height:320px; display:none; padding:10px">
<button onclick="open()">1</button>
<button onclick="document.getElementById('2').style.display='block'">2</button>
<button onclick="document.getElementById('3').style.display='block'">3</button>
I'd use event delegation to watch for clicks on the container. When the nth button is clicked, select the nth image, and toggle a class that hides/shows the image:
const images = document.querySelectorAll('img');
const buttons = [...document.querySelectorAll('button')];
document.addEventListener('click', (e) => {
if (e.target.matches('button')) {
const i = buttons.indexOf(e.target);
images[i].classList.toggle('hidden');
}
});
.hidden {
display: none;
}
<img id="1" src="https://www.gravatar.com/avatar/34932d3e923ffad9a4a1423e30b1d9fc?s=48&d=identicon&r=PG&f=1" style="height:320px; padding:10px" class="hidden">
<img id="2" src="https://www.gravatar.com/avatar/978ec0c47934c4b04401a8f4b4fec8bd?s=32&d=identicon&r=PG&f=1" style="height:320px; padding:10px" class="hidden">
<img id="3" src="https://lh3.googleusercontent.com/-uIr21N5ccCk/AAAAAAAAAAI/AAAAAAAAHeg/ohNEkpJKXQA/photo.jpg?sz=32" style="height:320px; padding:10px" class="hidden">
<button>1</button>
<button>2</button>
<button>3</button>
Problems with your original code include:
You're trying to select the elements before they exist in the DOM
Elements do not have a display property - in order to check the style of an element, you have to access its .style property first (eg, someImage.style.display)
Similarly, to set the style of an element, you have to set a property of its style property (eg someImage.style.display = <newDisplay>). Setting the display attribute of the element won't do anything.
Try to avoid inline handlers if at all possible - they have many problems and are pretty much universally considered to be quite poor practice. Always attach listeners properly using Javascript instead, whenever that's an option.
The event listener is the better solution, but if you want to see a working code in your way:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>switchpics</title>
</head>
<script type="text/javascript">
var open = function(param) {
img = document.getElementById(param.innerHTML);
if (img.style.display == 'none'){
img.style.display = "block";
} else {
img.style.display = "none";
};
};
</script>
<body>
<img id="1" src="1.jpg" style="height:20px; display:block; padding:10px">
<img id="2" src="1.jpg" style="height:20px; display:none; padding:10px">
<img id="3" src="1.jpg" style="height:20px; display:none; padding:10px">
<button onclick="open(this)">1</button>
<button onclick="open(this)">2</button>
<button onclick="open(this)">3</button>
</body>
</html>
I have two forms present in a div, form1 is visible when the page loads, and if I click the next button form1 is hidden and form2 is shown, which is working as expected.
Now I want to achieve the reverse of above scenario which is on click of a back button, form2 should be hidden and form 1 is shown.
Here's javascript code I have so far..
function switchVisible() {
document.getElementById("disappear").innerHTML = "";
if (document.getElementById('newpost')) {
if (document.getElementById('newpost').style.display == 'none') {
document.getElementById('newpost').style.display = 'block';
document.getElementById('newpost2').style.display = 'none';
} else {
document.getElementById('newpost').style.display = 'none';
document.getElementById('newpost2').style.display = 'block';
}
}
}
So basically I am looking for a way to achieve toggle functionality for two forms present in the same div using javascript and setting their display property.
Use a variable stepCount and then according to the value of count display appropriate form.
Like initialise the stepCount with 0, then on click of next increment it by 1 and check condition if stepCount is 1 show second form
Similarly from there if back button is pressed decrement the stepCount by 1 and check condition if stepCount is 0 show first form
Do all this on click of appropriate button click event
Make two button elements
<button id="next"></button>
<button id="back"></button>
You can use jquery (or plain javascript) for this, but I personally prefer jquery.
$("#next").click(function {
$("#newpost").hide();
$("#newpost1").show();
});
$("#back").click(function {
$("#newpost").show();
$("#newpost1").hide();
});
(Here 'newpost' and 'newpost1' are the id's of the two form elements)
You can use a similar format if you want to use plain javascript.
Add this
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</head>
You can also use link button and provide URL for particular form in this and hide back link button when click on back that time show only Next button.
e.g.
Next
Previous
$("#btnNext").click(function {
$("#btnNext").hide();
$("#btnPrevious").show();
});
$("#btnPrevious").click(function {
$("#btnPrevious").show();
$("#btnNext").hide();
});
You can use toggle function to show hide div.
$('#newpost2').hide();
$("#Toggle").click(function() {
$(this).text(function(i, v) {
return v === 'More' ? 'Back' : 'More'
});
$('#newpost, #newpost2').toggle();
});
.one {
height: 100px;
width: 100px;
background: #eee;
float: left;
}
.two {
height: 100px;
width: 150px;
background: #fdcb05;
float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='Toggle' class='pushme'>More</button>
<div class="one" id='newpost'>
<p>Show your contain</p>
</div>
<div class="two" id='newpost2'>
<p>Hide your contain</p>
</div>
This fiddle for button disappear:
$("#next").click(function()
{
$("#next").hide();
$("#back").show();
});
$("#back").click(function() {
$("#back").show();
$("#next").show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<input type="button" id="next" value="Next"/>
<input type="button" id="back" value="Back"/>
<button class="btn btnSubmit" id="Button1" type="button" value="Click" onclick="switchVisible();">NEXT</button>
<button type="button" class="btn btnSubmit" onclick="previousVisible();" >BACK</button>
simply use this jquery:
function switchVisible()
{
$("#newpost").hide();
$("#newpost2").show();
}
function previousVisible()
{
$("#newpost").show();
$("#newpost2").hide();
}
your updated fiddle
Or you may do like this:
<button class="btn btnSubmit" id="Button1" type="button" value="Click" onclick="form(1);">NEXT</button>
<button type="button" class="btn btnSubmit" onclick="form(2);" >BACK</button>
function form(a)
{
if(a==1)
document.getElementById("newpost").style.display="none";
else
document.getElementById("newpost2").style.display="block";
}
I'm using javascript to show a hidden div by clicking a button. After the div is displayed, I want to be able to click the button again and hide the div, and so on...
Here is my javascript:
<script type="text/javascript">
function showDiv() {
document.getElementById('dropdownText').style.display = "block";
}
</script>
This is the button:
<input type="button" name="answer" value="+" onclick="showDiv()" />
This is the hidden div:
<div id="dropdownText" style="display:none;">
This is the dropdown text.
</div>
You can e.g. bind specified class to the element and just toggle it.
function showDiv() {
document.getElementById('dropdownText').classList.toggle("hidden");
}
.hidden {
display: none;
}
<input type="button" name="answer" value="+" onclick="showDiv()" />
This is the hidden div:
<div id="dropdownText" class='hidden'>
This is the dropdown text.
</div>
If you tagged this question with jQuery as well, so I guess you could use the .toggle function, like this -
$('#answer').click(function() {
$('#dropdownText').toggle();
}
If you want to stick up with javascript only, your showDiv() function should look like this -
function showDiv() {
let text = document.getElementById('dropdownText');
if (text.style.display === 'none') {
text.style.display = 'block';
}
else {
text.style.display = 'none';
}
}
You should capture the current style every time a button is clicked, since you want to 'toggle' it back to the opposite state.
You simply need to do this:
const drop = document.getElementById('dropdownText')
const toggleDropdown = _ => {
const cl = drop.classList
cl.contains('hide')?cl.remove('hide'):cl.add('hide')
}
#dropdownText.hide {display:none}
/* DropDown Styles for this demo */
#dropdownText {width: 10em; height: 4em; background: green}
<button onclick='toggleDropdown()'>Toggle Div</button>
<div id='dropdownText'></div>
Note: Click Run Code Snippet to see the code in action.
The way it works is by detecting if it has the hide class and based on that, toggle that class.
The actual hiding and showing is done via CSS!
<div id="dropdownText" style="display:none">
This is the dropdown text.
</div>
<script type="text/javascript">
function showDiv() {
var x = document.getElementById('dropdownText');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
</script>
When I click the show/hide buttons above the tag, it works fine. But for the button below that (front full) it won't hide the contents of the tag. If i move the button above the beginning tag it will work. How can I get it to link to the hide tag above it?
<input type="button" onclick="show(this);" value="show"/>
<input type="button" onclick="hide(this);" value="hide"/>
<hide class="inner" style="display.none;">
<input type="button" onclick="showSpoiler1(this);" value="Front flip variaion (ramp)" />
<input type="button" onclick="showSpoiler2(this);" value="Front flip variaion (flat)" />
<input type="button" onclick="showSpoiler3(this);" value="Backflip variations" />
<input type="button" onclick="showSpoiler4(this);" value="Sideflip Variations (ramp)" />
<input type="button" onclick="showSpoiler5(this);" value="Twists and other tricks" />
<div1 class="inner" style="display:none;">
<ul>
<input type="button" onclick="hide(this);" value="Front full"/>
<li>Double Front</li>
<li>Aerial Twist</li>
</ul>
</div1>
</hide>
JS
function show(obj)
{
var inner = obj.parentNode.getElementsByTagName("hide")[0];
inner.style.display = "";
}
function hide(obj)
{
var inner = obj.parentNode.getElementsByTagName("hide")[0];
inner.style.display = "none";
}
In the buttons below, you have:
<div1 class="inner" style="display:none;">
<ul>
<input type="button" onclick="hide(this);" value="Front full"/>
<li>Double Front</li>
then in the function:
function show(obj)
{
var inner = obj.parentNode.getElementsByTagName("hide")[0];
So when you click on the button, obj is a reference to the button. It's parent node will be an LI that will be inserted by error correction (since a button can't be a child of a UL element). That parent node doesn't have a child "hide" element.
Even if the button was a child of the UL, it doesn't have any hide children either. Consider instead:
var inner = document.getElementsByTagName("hide")[0];
you can't you the same hide() function for both buttons , as what it does is pretty specific as to what it hides. why don't you try something like :
function hideParent(obj)
{
var inner = obj.parentNode.parentNode;
inner.style.display = "none";
}
<hide class="inner" style="display.none;">
...
<div1 class="inner" style="display:none;"> // <- assuming this is what this supposed to nbe hidden
<ul>
<input type="button" onclick="hideParent(this);" value="Front full"/>
<li>Double Front</li>
<li>Aerial Twist</li>
</ul>
</div1>
</hide>
if all the buttons are supposed to hide the same thing - the <hide> element then do something like this:
function hide(obj)
{
var inner = getElementbyTagName("body").getElementsByTagName("hide")[0];
inner.style.display = "none";
}
like the other comments suggest , don't use <hide> just use <div> then use getElementById
Your hide and show functions look for hide tags that are children of the button's parent, i.e. siblings of the button. The parent of the button is the div, and the parent of the div is the hide.
If you want the button to affect the hide element that contains it, try hide(this.parentNode.parentNode)
Or, you could change the hide/show functions to iterate progressively higher in the DOM hierarchy until it finds a hide element, so it will work for siblings, parents, and siblings of parents. Perhaps something like:
function hide(obj)
{
if (obj !== document)
{
var parent = obj.parentNode;
var inner = parent.getElementsByTagName("hide");
if (inner.length > 0)
{
inner[0].style.disply = "none";
} else {
hide(parent)
}
}
}