Toggle (show/hide) element with javascript - javascript

By using this method I can show/hide an element by using 2 buttons:
<script type="text/javascript">
function showStuff(id) {
document.getElementById(id).style.display = 'block';
}
function hideStuff(id) {
document.getElementById(id).style.display = 'none';
}
</script>
<input type="button" onClick="hideStuff('themes')" value="Hide">
<input type="button" onClick="showStuff('themes')" value="Show">
<div id="themes" style="display:block">
<h3>Stuff</h3>
</div>
Is there a method to use a single button?? Maybe if & else?

You've already answered your question...the use of if/else:
function toggle(id) {
var element = document.getElementById(id);
if (element) {
var display = element.style.display;
if (display == "none") {
element.style.display = "block";
} else {
element.style.display = "none";
}
}
}
This won't be completely foolproof, in case you are hiding/showing inline or inline-block elements, or if you are using non-default values for display on elements...such as setting a div's display to "inline" (for whatever reason) and then trying to use this function

Yes if/else will work
function toggle(id){
var elem = document.getElementById(id);
if(elem.style.display == 'block'){
elem.style.display == 'none'
} else if(elem.style.display == 'none'){
elem.style.display == 'block'
}
}

I think you mean something like this:
function toggle(id){
var elem = document.getElementById(id);
if(elem.style.display == "block"){
elem.style.display="none";
} else {
elem.style.display="block";
}
}

Here is an alternate solution. Instead of using document.getElementById, you can also use document.querySelector which returns the first Element within the document that matches the specified selector, or group of selectors.
Solution Code:
function toggleShow() {
var elem = document.querySelector(id);
if(elem.style.display == 'inline-block'){
elem.style.display="none";
}
else {
elem.style.display = "inline-block";
}
}

Related

div needs to be clicked twice to trigger event listener js

When I click on the .current-pet-icon div, I need to click it twice before it shows my menu. but every subsequent click after is okay. Just when I refresh / load the page the first time I need to double click. Any help wpuld be greatly appreciated!
Javascript
const menuToggle = document.querySelector('.current-pet-icon')
const openedNav = document.querySelector('.nav-popout');
const shadowNav = document.querySelector('.shadow-nav');
menuToggle.addEventListener('click', () => {
if (openedNav.style.display === "none") {
openedNav.style.display = "block";
shadowNav.style.display = "block";
} else {
openedNav.style.display = "none";
shadowNav.style.display = "none";
}
});
shadowNav.addEventListener('click', () => {
if (openedNav.style.display = "block") {
openedNav.style.display = "none";
shadowNav.style.display = "none";
}
});
HTML
<div class="pet-icon-container">
<img class="current-pet-icon" src="https://www.burgesspetcare.com/wp-content/uploads/2021/08/Hamster.jpg" alt="current pet icon">
</div>
Assuming that there is a CSS style assigned to hide both .nav-popout and .shadow-nav elements initially then a modified version of the original js code appears to function as expected.
const menuToggle = document.querySelector('.current-pet-icon')
const openedNav = document.querySelector('.nav-popout');
const shadowNav = document.querySelector('.shadow-nav');
menuToggle.addEventListener('click', (e)=>{
openedNav.style.display = openedNav.style.display == 'block' ? 'none' : 'block';
shadowNav.style.display = shadowNav.style.display == 'block' ? 'none' : 'block';
});
shadowNav.addEventListener('click', (e)=>{
if( openedNav.style.display == "block" ) {
shadowNav.style.display = openedNav.style.display = "none";
}
});
.pet-icon-container img{
width:150px;
}
.nav-popout,
.shadow-nav{
display:none;
}
<div class="pet-icon-container">
<img class="current-pet-icon" src="https://www.burgesspetcare.com/wp-content/uploads/2021/08/Hamster.jpg" alt="current pet icon" />
</div>
<div class='nav-popout'>#NAV-POPOUT#</div>
<div class='shadow-nav'>#SHADOW-NAV#</div>
A quick console.log(openedNav.style.display) will help you find the issue. In the first call to the click handler, openNav.style.disply is actually empty (not 'none').
Why does this happen
If you access a DOM Element via getElementById, you'll not be able to read the computed style of that element, because it is defined inside the CSS file (I assume you are doing that).
How to fix it
use getComputedStyle. Or see the top answers to these questions if you wanna know more:
document.getElementById(...).style.display is blank
myDiv.style.display returns blank when set in master stylesheet
menuToggle.addEventListener("click", () => {
if (getComputedStyle(openedNav).display=== "none") {
openedNav.style.display = "block";
shadowNav.style.display = "block";
} else {
openedNav.style.display = "none";
shadowNav.style.display = "none";
}
});

Hide and Show DIV using strict javascript with no embedded JS or CSS

I have searched and searched over so many previously answered questions and to my surprise, NONE of them answer what I am trying to accomplish. with JQuery this is easy but I am struggling with strict javascript.
I cannot have any embedded JS OR CSS in the html...
This is what I have so far:
function showhide()
{
var billingaddress = document.getElementById("billingaddress");
if (billingaddress.style.display === "block")
{
billingaddress.style.display = "none";
}
else if (billingaddress.style.display === "none")
{
billingaddress.style.display = "block";
}
}
function init ()
{
var billingcheckbox = document.getElementById("billing");
if (billingcheckbox.checked)
{
showhide();
}
else
{
showhide();
}
It is hidden by default using CSS.
Cheers,
With he code you've provided, it can be done like this.
billingaddress.style.display is empty by default, you can easily check it in the if without a comparison.
function showhide() {
if (billingaddress.style.display) billingaddress.style.display = ""
else billingaddress.style.display = 'none';
}
var billingaddress = document.getElementById("billingaddress")
var billingcheckbox = document.getElementById("billing")
billingcheckbox.addEventListener('change', showhide)
billingcheckbox.checked = true
showhide()
<input type="checkbox" id="billing"/> Hide
<div id="billingaddress">Lorem Ipsum</div>
It's as easy as this:
this keyword inside event handler references checkbox element so you can get checkbox state with this.checked property.
<input type="checkbox" id="billing">
<input type="text" id="billingaddress" placeholder="Address" style="display:none">
<script>
var billingAddress = document.getElementById("billingaddress");
var billingCheckbox = document.getElementById("billing");
billingCheckbox.addEventListener('click', function(event) {
billingAddress.style.display = this.checked ? "block" : "none";
})
</script>
The code below should do it -- but to be sure make sure all your IDs are matching up with what is in the HTML markup:
function showhide(show) {
var billingaddress = document.getElementById("billingaddress");
if (show) {
billingaddress.style.display = "block";
} else {
billingaddress.style.display = "none";
}
}
function init () {
var billingcheckbox = document.getElementById("billing");
if (billingcheckbox.checked) {
showhide(true);
} else {
showhide(false);
}
}

How to show/hide a div in javascript?

When i click the button i want the div to show, and when i click the button again i want it to disappear. What am i doing wrong?
<button type="button" onclick="myFunction()">Click Me!</button>
<div id="Dglow" class="Dglow">
Glow
</div>
<script>
function myFunction() {
var e = document.getElementById("Dglow").style.display;
if (e == "none")
e = "block";
else {
e = "none";
}
}
You should compare and change element's display property:
function myFunction() {
var e = document.getElementById("Dglow").style;
if (e.display == "none") {
e.display = "block";
} else {
e.display = "none";
}
}
<button type="button" onclick="myFunction()">Click Me!</button>
<div id="Dglow" class="Dglow">Glow</div>
Actually document.getElementById("Dglow").style.display returns a string and according to Left hand assignment rule you cannot store anything to that string, since that string is not a variable/object now ie not a reference to DOM anymore
You can do is
var e = document.getElementById("Dglow").style;
if(e.display == "none")
e.display = "block";
else{
e.display = "none";
}
Have you considered using Jquery? If so heres what you need.
$(document).ready(function(){
$("#button").click(function(){
$("#Dglow").toggle();
});
});
You would need to give your button an id for this though.

Javascript change display CSS

Im completely new to Javascript, this is what i want:
Guy clicks on an element, so i trigger an onclick and i want to run a JS function, all clear so i need a JS function, what this function needs to do:
Check if the display of element #mobilemenu is block or none.
When it is block change it to none, when its none change it to block.
What i found so far was this:
function Change(){
document.getElementById("mobilemenu").style.display = "block"; }
But i am stuck on checking if it is currently block or none. I am kinda new to JS so maybe it is super easy (as i think) but i can't find a proper tutorial or some examples.
Thanks in advance!
You can use an if/else statement to check whether the element is displayed, and then show or hide it accordingly:
function Change() {
/* Put the mobilemenu into a variable */
var mobilemenu = document.getElementById("mobilemenu");
/* Check the display property of the element's style object */
if (mobilemenu.style.display !== "block") {
/* The element isn't display: block; so show it */
mobilemenu.style.display = "block";
} else {
/* The element is display: block; so hide it */
mobilemenu.style.display = "none";
}
}
Just add an if-else.
function Change(){
var displayVal = document.getElementById("mobilemenu").style.display;
if (displayVal == "block")
document.getElementById("mobilemenu").style.display = "none";
else if (displayVal == "none")
document.getElementById("mobilemenu").style.display = "block";
}
Here is a Fiddle: http://jsfiddle.net/vaa9goLe/
Also, you can use getComputedStyle in case your element doesn't have initial display value to ensure your function will always work.
var element = document.getElementById('btn');
element.onclick = function() {
var mydiv = document.getElementById('mydiv'),
isVisible = (mydiv.currentStyle || window.getComputedStyle(mydiv, '')).display == 'block';
if (isVisible){
mydiv.style.display = 'none';
} else {
mydiv.style.display = 'block';
}
};
jsfiddle:
http://jsfiddle.net/ykypcmt2/
This may help you
<div id="mobilemenu" style="display:block"></div>
<script type="text/javascript">
function Change(){
var contentId = document.getElementById("mobilemenu");
contentId.style.display == "block" ? contentId.style.display = "none" :
contentId.style.display = "block";
}
</script>
If the div had style value anything other than block or none , the following code should do nothing and preserve the original style value.
function Change(){
document.getElementById("mobilemenu").style.display = ( document.getElementById("mobilemenu").style.display === "block" ) ? "none" : ( document.getElementById("mobilemenu").style.display === "none" ) ? "block" : document.getElementById("mobilemenu").style.display ;
}

How to open a hidden div when a hash is on the URL?

I'm using this javascript code to have a couple "show/hide" toggled divs on my site:
<script language="javascript">
function toggledean() {
var ele = document.getElementById("toggleTextdean");
var text = document.getElementById("displayTextdean");
if(ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "Show more";
}
else {
ele.style.display = "block";
text.innerHTML = "Hide";
}
}
</script>
What should I add to this code to have the div be displayed upon loading the page with a specific #hash added to the URL?
Thank you very much.
This is not the javascript answer that you want, but you could try playing around with the :target pseudo selector. For instance,
<!-- HTML -->
<div id="foo">show this with #foo.</div>
<div id="bar">#bar shows this.</div>
<style type="text/css">
div {display: none}
:target {display: block}
</style>
Example: http://jsfiddle.net/ZAHns/4/ (thanks to Jared for the idea of adding the anchors).
Depending on what you are trying to do, this could possibly work, but think your requirements through.
Note: Take this response with a HUGE grain of salt -- don't use it.
To answer the actual question, use the following to determine if the hash is present:
var in_hash = location.hash.slice(1) === what_you_are_looking_for;
if (in_hash) ? /* IN HASH */ : /* NOT IN HASH */;
Something like this should work:
<script>
var hash = window.location.hash.replace('#', '');
if (hash) {
document.getElementById(hash).style.display = 'block'
}
</script>
If you've only got the one element, like your script has, you could just call the function to toggle it if any hash exists in the url:
<script type="text/javascript">
function toggledean() {
...
}
if (window.location.hash == '#dean') toggledean();
</script>
Or you could make your toggle script a little more universal:
<script type="text/javascript">
var hash = window.location.hash.replace('#', '');
function toggle (elementPartial) {
var ele = document.getElementById('toggleText'+elementPartial);
var text = document.getElementById('displayText'+elementPartial);
if(ele.style.display == 'block') {
ele.style.display = 'none';
text.innerHTML = 'Show more';
} else {
ele.style.display = 'block';
text.innerHTML = 'Hide';
}
}
if (hash) {
toggle(hash);
}
</script>
Additionally, you could make this a little simpler and more flexible using a javascript framework, like jQuery.
Others have answered the URL hash part, I'll just comment on the script:
> <script language="javascript">
The language attribute is deprecated, type is required, so:
<script type="text/javascript">
> function toggledean() {
> var ele = document.getElementById("toggleTextdean");
> var text = document.getElementById("displayTextdean");
>
> if(ele.style.display == "block") {
The default display property is '' (empty string) unless you have set it to "block" previously.
> ele.style.display = "none";
> text.innerHTML = "Show more";
> } else {
> ele.style.display = 'block';
> text.innerHTML = 'Hide';
> }
Given the very high probability that the div will have a display value of '' when first loaded, you are much better off testing for style.display = 'none', so:
if (ele.style.display == 'none') {
ele.style.display = '';
text.innerHTML = 'Hide';
} else {
ele.style.display = 'none';
text.innerHTML = 'Show more';
}

Categories