How to show a display:none DIV using Javascript - javascript

I have a DIV which has a display set to none, by using javascript I tried showing it by using the onclick of a button. But what happens is the exact opposite. My DIV is already shown and when I click the button it hides the DIV. What am i doing wrong here, please HELP!
This is my button and the div:
<button onclick="myFunction()">SHOW</button>
<div id="how_to_form">
<img src="../images/view.png">
</div>
This is the JS code:
function myFunction() {
var x = document.getElementById("how_to_form").style.display = 'none';
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}

Your line there has a double assignment:
var x = document.getElementById("how_to_form").style.display = 'none';
It first assigns the display to none:
document.getElementById("how_to_form").style.display = 'none';
and then takes the result of that expression (which is the string you assigned), and assigns it to x:
var x = 'none';
Which isn't what you want. First declare the variable for the element, then assign its style.
Also, it sounds like you want the element to start out hidden - assign its initial style outside the function:
const form = document.getElementById("how_to_form");
form.style.display = 'none';
function myFunction() {
if (form.style.display === "none") {
form.style.display = "block";
} else {
form.style.display = "none";
}
}
Or, to be more concise, use the conditional operator:
function myFunction() {
form.style.display = form.style.display === "none"
? 'block'
: 'none';
}
Also consider attaching the handler properly using Javascript, rather than using inline HTML attributes, which are generally considered to be pretty poor practice and can be hard to manage:
document.querySelector('button').addEventListener('click', myFunction);

have you checked if you have already set a default style to your div?
you either have to set your div's default style to display:none by inline
<div id="how_to_form" style="display:none">
or by css
<style>
#how_to_form{ display:none }
</style>

Issue is your variable assignment
Chaining the assignment operator is possible in order to assign a single value to multiple variables.
Please refer this link for variable assignment options
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators
var x = y= 10
Then both x and y values are 10
Similarly in your code var x is none
To achieve expected result , use below option
1. set CSS for html_to_form to display:none
2.In your code change variable x assignment to
var x = document.getElementById("html_to_form")

Related

Display div when inline style none

I have a submit button that uses Gravity Forms to conditionally show or hide the button.
When the button is shown the code looks like: <button class="button gform_button" id="gform_submit_button_1" style="">
When the button is not shown the code looks like: <button class="button gform_button" id="gform_submit_button_1" style="display: none;">
So, what I wanted to do was display a div when the button is not displayed or has the inline style display: none.
I thought I could do something like this:
function myFunction() {
var x = document.getElementById('gform_submit_button_1');
if (x.style.display = 'none') {
document.getElementById("div1").style.display = "block";
} else {
document.getElementById("div1").style.display = "none";
}
}
<div id="div1">This is a hidden div that we can show with JavaScript</div>
This shows div1 when the page loads, but when style="" the div does not hide. When the condition is true and style="" the page does not refresh, which is probably the issue. Is there a way to tweak things so that when style="" div1 is not shown?
Thanks,
Josh
if (x.style.display = 'none')
This should be:
if (x.style.display == 'none')
otherwise, the if statement will return true in all cases, and the x.style.display property will be always 'none'.
As in the comment section, = is used for assignment, == for value comparison whereas === is used for type and value comparison.
And for this,
When the condition is true and style="" the page does not refresh,
which is probably the issue.
you should call the function somewhere so it can be executed after the page loading.
Alternatively, you could also simply add a Gravity Form HTML field with your alternative div inside. Then use conditional logic to show it when the submit button is hidden.
As the queue for editing of answer from #Dream Bold is full this is my answer regarding to this question based on the previous Answer.
Basically clarification
Following line of code:
if (x.style.display = 'none')
Should be changed to:
if (x.style.display == 'none')
Main difference is the operator used (==). In the first case by using "=" the if statement will always return true, and the x.style.display property will be always 'none'.
As in the comment section, = is used for assignment, == for value comparison whereas === is used for type and value comparison.
To learn more about expressions and operators: Check here
And regarding for following requirement
When the condition is true and style="" the page does not refresh,
which is probably the issue.
The problem in this is that the code is not executed.
You should first create function, then by adding event listeners or setting action which would call the previously created function so it can be executed after the page loading.
My suggestion is to use window.onload + another event listener/action attribute on element
Like this:
window.onload = function(){
var x = document.getElementById("gform_submit_button_1");
if(x.style.display == "none"){
alert("Display of x is none");
document.getElementById("div1").style.display = "block";
}
else{
alert("Display of x is not none");
document.getElementById("div1").style.display = "none";
x.style.display = "block";
}
}

Toggle Hiding/Showing an Element

I'm trying to have a couple of buttons to show and hide some pictures, I have gotten it to somewhat work, but when I start the webpage the pictures are already shown, when I try make them invisible at start. I have tried swapping the "block" and "none" sentences in the function, but it just made the button less responsive.
javascript part:
function bassnectar() {
var x = document.getElementById("myDIV3");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
html part:
<button onclick="bassnectar()">Bassnectar</button>
<div id="myDIV3">
<img src="/images/bassnectar.jpg">
</div>
What you’re missing is that you’re assuming that block elements have a default display value of block. Which would be intuitive.
Such is not the case though.
The initial value of display is the browser’s default. If you query the value of the display property on a new HTML element, you’ll get an empty string.
It doesn’t return block until you explicitly set its display to block.
Edit:
It's important to note that setting a value in CSS doesn't change the behavior. If you set a div to be display block in CSS, it will still return an empty string if you query it.
Here's a working example:
var block = document.createElement("div");
var inline = document.createElement("span");
console.log("Initial display values:")
console.log(`block.style.display: ${block.style.display}`);
console.log(`inline.style.display: ${inline.style.display}`);
block.style.display = "block";
inline.style.display = "inline";
console.log("\nAfter setting them explicitly:")
console.log(`block.style.display: ${block.style.display}`);
console.log(`inline.style.display: ${inline.style.display}`);
div {
display: block !important;
}

How to show/hide multiple divs using if/else statement?

My goal is to display various divs conditionally, such that:
display "x" div if it's not already
display "y" div but only if "x" div is already being displayed
display "z" div but only if "x" and "y" div are already being displayed.
With this code I can toggle a div to display and then not display:
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
But then when I try do this for more than one div, it doesn’t work.
For example, this is what I tried:
function myFunction() {
var x = document.getElementById("myDIV");
var y = document.getElementById("myDIV2");
if (x.style.display === "none") {
x.style.display = "block";
} else if (y.style.display === "none") {
y.style.display = "block";
} else {
console.log("It worked!");
}
}
I made a couple CodePens showing those snippets:
This is the first snippet that works
This is the second one that doesn't
I would appreciate any help. Thank you!
So let's walk through it in the first myFunction. That will work reliably because there's only two options - "is x set to display: none? if so, do X; otherwise, do Y" will always work as expected because it is simple binary logic (all the cases are handled, it basically just toggles the style.display property). As soon as you bring more complicated logic into the equation and take multiple factors into consideration, it gets a little more slippery, and you need to formulate your approach more carefully.
The logic you basically want is, if X is hidden, show it; if y is hidden AND x is visible, show it; finally, if X is visible AND y is visible AND z is hidden, show it. You can write this in a really readable way by defining some quick isHidden(), isVisible(), and show() helper functions:
EDIT: FZs made a good point about classes not being caught by this logic. To account for that, all we need to do is add an "OR classList contains hidden" expression to the isHidden() check and voila.
// helpers
let isHidden = (el) => el.style.display == "none" || el.classList.contains('hidden'),
isVisible = (el) => !isHidden(el),
show = (el) => el.style.display = "block";
// elements
let x = document.getElementById("div-x"),
y = document.getElementById("div-y"),
z = document.getElementById("div-z");
// click handler
let handleClick = () => {
if (isHidden(x))
show(x);
else if (isHidden(y) && isVisible(x))
show(y);
else if (isHidden(z) && isVisible(y) && isVisible(x))
show(z);
else console.log("It worked!");
}
document.getElementById('btn').addEventListener('click', handleClick);
<div id="div-x" style="display:none">X</div>
<div id="div-y" style="display:none">Y</div>
<div id="div-z" style="display:none">Z</div>
<button id="btn">Click me!</button>
Because elem.style returns the inline style (style="/* styles */") of elem.
As #myDiv and #myDiv2 have only styles applied by stylesheets, x.style.display will return undefined, which isn't "none".
To solve it, I recommend toggling a .hidden class on the elements:
function myFunction() {
var x = document.getElementById("myDIV");
var y = document.getElementById("myDIV2");
if (x.classList.contains("hidden")) {
x.classList.remove("hidden");
} else if (y.classList.contains("hidden")) {
y.classList.remove("hidden");
} else {
console.log("It worked!");
}
}
.hidden{
display: none;
}
<div id="myDiv" class="hidden"></div>
<div id="myDiv2" class="hidden"></div>
Or, to show them alternately (I assume that was the goal):
function myFunction() {
var x = document.getElementById("myDIV");
var y = document.getElementById("myDIV2");
x.classList.toggle("hidden")
y.classList.toggle("hidden")
}
.hidden{
display: none;
}
<div id="myDiv"></div>
<div id="myDiv2" class="hidden"></div>

Javascript function for showing/hiding content of div on button click not working

Javascript newbie here. This is basically what I'm working with.
The function below is intended to hide everything enclosed in the newsDisplay class, but nothing happens when clicking the button that calls it.
function showHide() {
var x = document.getElementsByClassName('newsDisplay');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
.newsDisplay {
display: block;
}
<h1>News<button onclick="showHide();"><img src="..\Images\showHide.png"></button></h1>
<div class="newsDisplay">
<div class="bodyBox">
<h2>Diablo 3</h2>
TEXT/PARAGRAPHS
</div>
</div>
Manually changing display: block; to display: none; behaves exactly as expected, so either the syntax or logic of the function is incorrect, or something is preventing the function from executing when clicking the button.
Could really use some help, thank you!
Try the first element of this class as follows
var x = document.getElementsByClassName('newsDisplay')[0];
Document document.single getElementsByClassName() will return an array of elements with the same class. It is different from document.getElementById() in so far as the latter returns a DOM object rather than an array of DOM objects.
As stated from it's name getElementsByClassName get elements (and not single element), so result of this function call is a collection of elements.
To access to first element of collection you can:
x = document.getElementsByClassName('newsDisplay')[0];
// or
X = document.getElementsByClassName('newsDisplay').item(0);
You can try a loop if you want multiple of the page. The key is you're grabbing a list of elements with the class, since classes aren't unique identifiers. You can either use my code below or switch it to an id and grab it by document.getElementById. Notice the s in document.getElementsByClassName
var x = document.getElementsByClassName('newsDisplay');
function showHide() {
for (var i = 0; i < x.length; i++){
x[i].style.display === 'none'
? x[i].style.display = 'block'
: x[i].style.display = 'none';
}
}
<h1>News<button onclick="showHide();"><img src="..\Images\showHide.png"></button></h1>
<div class="newsDisplay">
<div class="bodyBox">
<h2>Diablo 3</h2>
TEXT/PARAGRAPHS
</div>
</div>
<h1>News<button onclick="showHide();"><img src="..\Images\showHide.png"></button></h1>
<div class="newsDisplay">
<div class="bodyBox">
<h2>Diablo 3</h2>
TEXT/PARAGRAPHS
</div>
</div>
Try the code below.
Use this
var x = document.getElementsByClassName('newsDisplay')[0];
function showHide() {
var x = document.getElementsByClassName('newsDisplay')[0];
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
.newsDisplay {
display: block;
}
<h1>News<button onclick="showHide();"><img src="..\Images\showHide.png"></button></h1>
<div class="newsDisplay">
<div class="bodyBox">
<h2>Diablo 3</h2>
TEXT/PARAGRAPHS
</div>
</div>
If you hit F12, navigate to the sources tab (on google chrome) you can set a breakpoint on your javascript function, your code is running, but you are getting a
Uncaught TypeError: Cannot read property 'display' of undefined
The reason for this is getElementsByClassName is returning a list of elements with that class selector, not just the one. If you want to just do this to the first element you can simply do:
function showHide() {
var x = document.getElementsByClassName('newsDisplay')[0];
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}

JavaScript onclick requires two clicks

My problem is that when onclicktriggers the toggleNew function it's not executing but when I click the div a second time it's executing just as it should...
HTML:
<div id="aside_main">
<div onclick="toggleNew();">click</div>
content
</div>
<div id="aside_new">
content
</div>
JS:
function toggleNew() {
var e = document.getElementById('aside_main');
var se = document.getElementById('aside_new');
if(e.style.display == 'block') {
e.style.display = 'none';
se.style.display = 'block';
} else {
e.style.display = 'block';
se.style.display = 'none';
}
}
CSS:
#aside_main {
display: block;
}
#aside_new {
display: none;
}
What is happening here and how can I make the function work the first time a user clicks the div?
This will not work properly because you are using following line inside 'div#aside_main' which is going to be hidden.
<div onclick="toggleNew();">click</div>
Try keeping it outside like this-
<div onclick="toggleNew();">click</div>
<div id="aside_main">
content
</div>
<div id="aside_new">
content2
</div>
Also in javascript it is not checking for 'e.style.display' first time in if condition.
Try using
if(e.offsetWidth > 0 || e.offsetHeight > 0){
e.style.display = 'none';
se.style.display = 'block';
}
else
{
e.style.display = 'block';
se.style.display = 'none';
}
You need to call the function like onclick="toggleNew();" in the div onclick. I just added your code in fiddle.
May not be the best answer, but the fix was to use inline css by style attribute.
Like this:
<div id="aside_main" style="display: block; border: 2px solid green;">
<div onclick="toggleNew();">click</div>
content
</div>
<div id="aside_new" style="display: none; border: 2px solid red;">
content
</div>
e.style.display represents the style of the element defined by the style attribute, it does not give you the computed style. to get the computed style use
if (window.getComputedStyle(e,null).getPropertyValue("display") == 'block){
I had the same double click required issue. I was using an internal style sheet which was correctly setting the display like this.
When loading the HTML file #YourID was not visible as expected.
#YourID {
display: none;
}
When clicking the button tied to the function I noticed that the first click set the inline display to style="display: none;". The second click set the inline style="display: block;" and of course then it displayed as expected.
I found that I needed to set the element directly inline with style="display: none;" and just removed the intern style sheet entry (Above "#YourID").
I'm doubtful that this is 100% the correct answer in every scenario but it would seem the underlying issue is caused by the element not being set in the appropriate initial state for the function to act on it properly.
https://jsfiddle.net/em05a1kf
<div id="YourID" style="display: none;">
<b>Super Hidden Content</b>
</div>
<button onclick="ToggleID('YourID');">Do Foo</button>
<script type="text/javascript">
function ToggleID(idname) {
var x = document.getElementById(idname);
(x.style.display === "none") ? (x.style.display = "block") : (x.style.display = "none");
return false;
}
</script>
In your condition : Use onclick="toggleNew();" // calling
This is the way to call a function.
And if you want to Pass the function then you use only toggleNew //passing
They are two different activities.
Here is another way of doing that. You just need to add two lines to your javascript code-
document.getElementById('aside_main').style.display='block';
document.getElementById('aside_new').style.display='none';
set initial display property in javascript. This will work fine.
One way (for me the simplest way) to solve this is by counting clicks.
For this purpose you set the new intiger variable click to 0 outside of your function toggleNew() and everytime you call your function you increase variable click for 1 like this:
<script> var click = 0;
function toggleNew() {
click = click +1;
var e = document.getElementById('aside_main');
var se = document.getElementById('aside_new');
if (click > 1) {
if(e.style.display == 'block') {
e.style.display = 'none';
se.style.display = 'block';
} else {
e.style.display = 'block';
se.style.display = 'none';
}
} else {
e.style.display = 'none';
se.style.display = 'block';
}
}
</script>

Categories

Resources