i want to show and then hide div but when i click the button it do not work for the first time, when i click second time it works normally.
i want that it works on first click.
HTML
<p>Click the button</p>
<button onclick="myFunc()">Try it</button>
<div id="divi">
Div region
</div>
CSS
#divi {
width: 50%;
padding: 50px 0;
text-align: center;
background-color: #ccc;
margin-top:20px;
display:none;
}
Javascript
function myFunc() {
var dv = document.getElementById('divi');
if (dv.style.display ==='none') {
dv.style.display = 'block';
} else {
dv.style.display = 'none';
}
}
Here is the pen: https://codepen.io/animaxf/pen/xdVVbK
This is because technically, the style attribute is empty so style.display is actually null. So it first of all makes it display:none; on first click.
If you change the JavaScript to be:
function myFunc() {
var dv = document.getElementById('divi');
if (dv.style.display === 'block') {
dv.style.display = 'block';
} else {
dv.style.display = 'none';
}
}
Basically checking it is block first - it will work.
function myFunc() {
var dv = document.getElementById('divi');
if (dv.style.display === 'block') {
dv.style.display = 'none';
} else {
dv.style.display = 'block';
}
}
#divi {
width: 50%;
padding: 50px 0;
text-align: center;
background-color: #ccc;
margin-top:20px;
display:none;
}
<p>Click the button</p>
<button onclick="myFunc()">Try it</button>
<div id="divi">
Div region
</div>
First click let it fall to the else statement and display it.
After that you are in a good loop.
function myFunc() {
var dv = document.getElementById('divi');
if (dv.style.display == 'block') {
dv.style.display = 'none';
} else {
dv.style.display = 'block';
}
}
#divi {
width: 50%;
padding: 50px 0;
text-align: center;
background-color: #ccc;
margin-top:20px;
display: none;
}
<body>
<p>Click the button</p>
<button onclick="myFunc()">Try it</button>
<div id="divi">
Div region
</div>
</body>
Add this
<div id="divi" style="display:none">
The first time, display is not defined for your div
When you click for the first time there is no style applied (dv.style.display = "") hence, dv.style.display!== 'none' becomes true and dv.style.display = 'none' gets applied.
function myFunc() {
var dv = document.getElementById('divi');
if (dv.style.display !=='none'&& dv.style.display !=="") {
dv.style.display = 'none';
} else {
dv.style.display = 'block';
}
}
#divi {
width: 50%;
padding: 50px 0;
text-align: center;
background-color: #ccc;
margin-top:20px;
display:none;
}
<body>
<p>Click the button</p>
<button onclick="myFunc()">Try it</button>
<div id="divi">
Div region
</div>
</body>
There is no display property set when you click the first time. Just switched the properties – it will work.
https://codepen.io/anon/pen/XRddvd
The first time you click the button, the CSS property display doesn't set yet, therefore when click occurs it checks rather dv.style.display !== 'none' while actually dv.style.display === ''
You can fix this in your code, or you can simply change the CSS as it is more elegant solution. Just apply display: block (or display: none according to your wishful starting state) to #divi inside it's CSS definition.
That is because you change the style of the div, but the display:none attribute is inside the class element. So, the first time the div have not the display attribute and it declare it as none. To fix this, put style="display:none; on the div instead of declaring it inside the css file
When you first load the page, the class is undeclared meaning that you statement if (dv.style.display !=='none') will return true and then apply a display propert dv.style.display = 'none';
Instead, you should use if (dv.style.display =='block') to check whether it is shown.
function myFunc() {
var dv = document.getElementById('divi');
if (dv.style.display =='block') {
dv.style.display = 'none';
} else {
dv.style.display = 'block';
}
}
#divi {
width: 50%;
padding: 50px 0;
text-align: center;
background-color: #ccc;
margin-top:20px;
display:none;
}
<body>
<p>Click the button</p>
<button onclick="myFunc()">Try it</button>
<div id="divi">
Div region
</div>
</body>
Related
This question already has answers here:
Why do I have to click this input button twice to call a function?
(4 answers)
Closed 1 year ago.
Below I have 2 pieces of code. The purpose of the code is to alternate between showing and hiding an element by clicking on the button.
Logically, I feel both pieces of code are sound and should work in exactly the same way. However, #1 functions as required whilst #2 doesn't. #2 requires 2 presses of the button to first display the element. After that, it functions as required.
I assume I have made a mistake linked to nomenclature, but I am unable to pinpoint it. Please help in doing so.
#1
<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
visibility: hidden;
}
</style>
</head>
<body>
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
This is my DIV element.
</div>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.visibility === "hidden") {
x.style.visibility = "visible";
} else {
x.style.visibility = "hidden";
}
}
</script>
</body>
</html>
#2
<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
visibility: hidden;
}
</style>
</head>
<body>
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
This is my DIV element.
</div>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.visibility === "visible") {
x.style.visibility = "hidden";
} else {
x.style.visibility = "visible";
}
}
</script>
</body>
</html>
That's happening because the x.style returns inline style for an element (the value sets on the div tag <div id="myDIV" style="/*this value*/"> and not the overall element styling) which is empty by default , think of it as any other HTML attributes like id or width.
So what you want to do, is to declare the visibility propriety inside the div like so :
<div id="myDIV" style="visibility: hidden;">
this way x.style.visibility will return 'hidden' from the first time.
Here are two snippets so you see the difference:
The same as your code just added a console.log
<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
visibility: hidden;
}
</style>
</head>
<body>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
console.log('x.style.visibility = '+x.style.visibility);
if (x.style.visibility === "hidden") {
x.style.visibility = "visible";
} else {
x.style.visibility = "hidden";
}
}
</script>
<div id="myDIV">
This is my DIV element.
</div>
</body>
</html>
and now if we set visibility as an inline style
<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
</style>
</head>
<body>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
console.log('x.style.visibility = '+x.style.visibility);
if (x.style.visibility === "hidden") {
x.style.visibility = "visible";
} else {
x.style.visibility = "hidden";
}
}
</script>
<div id="myDIV" style="visibility: hidden;">
This is my DIV element.
</div>
</body>
</html>
account for starting condition
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.visibility === "hidden" || !x.style) {
x.style.visibility = "visible";
} else {
x.style.visibility = "hidden";
}
}
I have a menu that open a sub-menu section onclick (let's name the container: "sub-menu").
I would like "sub-menu" to disapear if the user click outside of it / on the rest of the page.
It seems to be solved on How do I detect a click outside an element?
But I can't get how to use the code snipet from the second most popular answer:
export function hideOnClickOutside(selector) {
const outsideClickListener = (event) => {
const $target = $(event.target);
if (!$target.closest(selector).length && $(selector).is(':visible')) {
$(selector).hide();
removeClickListener();
}
}
const removeClickListener = () => {
document.removeEventListener('click', outsideClickListener)
}
document.addEventListener('click', outsideClickListener)
}
Could you please guide me on how to use it?
I edited, and included a basic example. -> I want sub menu to also close when clicking on the "white" space. But not on the parent "main menu" element.
document.getElementById("main-menu").addEventListener("click", function() {bouttonexpand('sub-menu-class')});
function bouttonexpand(id) {
var elemeacacher = document.getElementsByClassName(id);
if (elemeacacher[0].style.display != "none"){
for(var y=0;y<elemeacacher.length;y++)
elemeacacher[y].style.display = "none";
}
else {
for(var y=0;y<elemeacacher.length;y++)
elemeacacher[y].style.display = "block";
}
}
#main-menu {
display:inline-block;
height:20px;
width:100px;
background: blue;
padding: 5%;
}
#sub-menu {
display:inline-block;
height:50px;
width:50px;
background: red;
display: none;
}
<div><div id="main-menu">Main menu</div></div>
<div><div id="sub-menu" class="sub-menu-class">Sub menu</div></div>
Thanks
By using jQuery, you can bind to the document click event and hides the div container when the clicked element isn’t the container itself or descendant of the div element.
var container = $("#sub-menu");
if (!container.is(event.target) && !container.has(event.target).length) {
container.hide();
}
If you want to hide that container without being tested the container itself or descendant of the div element just remove the condition and simply use container.hide();.
Also, rather than setting display: none; on sub-menu in the CSS, set it manually so that you can toggle the sub-menu from the very first click.
Have a look at the snippet below:
var x = document.getElementById("sub-menu");
x.style.display = "none";
$(document).click(function (evt) {
if ($(evt.target).is('#main-menu')) { // control click event if it's main-menu
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
else {
var container = $("#sub-menu");
if (!container.is(event.target) && !container.has(event.target).length) { // if you don't want that remove the condition and write container.hide(); only
container.hide();
}
}
});
#main-menu {
display: inline-block;
height: 20px;
width: 100px;
background: blue;
padding: 5%;
}
#sub-menu {
display: inline-block;
height: 50px;
width: 50px;
background: red;
}
<script src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<div id="main-menu">Main menu</div>
<div id="sub-menu" class="sub-menu-class">Sub menu</div>
This question already has answers here:
why javascript this.style[property] return an empty string? [duplicate]
(2 answers)
Closed 2 years ago.
i have a div and button i click the button fist time no response and click again and show
function banne() {
var ban = document.getElementById("content");
//consloe.log(ban.style.display === "none");
if (ban.style.display === "none") {
ban.style.display = "block";
} else {
ban.style.display = "none";
}
}
.banner-content {
display: none;
height: 100px;
color: #fff;
background: #1b1b1b;
}
<button class="banner" onclick="banne()"> know </button>
<div class="banner-content" id="content">
Some Data
</div>
here the console value show false value but i write the style inline style="display:none" in div class banner-content it working, why the style sheet value not taken ,any idea?
Javascript can't access the style mentioned in the CSS file with the ban.style.display. You have to use getComputedStyle() method.
window.getComputedStyle(ban, null).getPropertyValue("display");
But in your case I think it is better use a class based toggle maybe like,
CSS
.banner-content {
display: none;
height: 100px;
color: #fff;
background: #1b1b1b;
}
.banner-content.active {
display: block;
}
JS
function banne() {
var ban = document.getElementById("content");
ban.classList.toggle("active");
}
While style doesn't register the stylesheet properties, you can check if the style does not equal to "block" and then set it to block, otherwise none. Also see the difference between getComputedStyle and style: https://developer.mozilla.org/en/DOM/window.getComputedStyle
function banne() {
var ban = document.getElementById("content");
//consloe.log(ban.style.display === "none");
if (ban.style.display !== "block") {
ban.style.display = "block";
} else {
ban.style.display = "none";
}
}
.banner-content {
display: none;
height: 100px;
color: #fff;
background: #1b1b1b;
}
<button class="banner" onclick="banne()"> know </button>
<div class="banner-content" id="content">
Some Data
</div>
It's generally not a good idea to use inline event handlers.
Add a listener to the document. To toggle display, use a separate css class (.visible in the snippet) and toggle that. It makes your life so much easier.
document.addEventListener("click", banne);
function banne(evt) {
if (evt.target.classList.contains("banner")) {
document.querySelector("#content").classList.toggle("visible");
}
}
.banner-content {
display: none;
height: 100px;
color: #fff;
background: #1b1b1b;
}
.banner-content.visible {
display: block;
}
<button class="banner"> know </button>
<div class="banner-content" id="content">
Some Data
</div>
This question already has answers here:
getElementsByClassName not working [duplicate]
(2 answers)
Closed 6 years ago.
I've written a script, it's goal is to stop displaying images one and two, while allowing image 3 to remain displayed and move into their place. It works fine when I use div Id's instead of div Classes, but I would prefer to use div classes so I can group the elements like this:
function myFunction() {
var y = document.getElementsByClassName("firstimage secondimage");
if (y.style.display === 'none') {
y.style.display = 'block';
} else {
y.style.display = 'none';
}
}
rather than this (in order to save space should I choose to include more elements):
function myFunction() {
var x = document.getElementById("firstimage");
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
var y = document.getElementById("secondimage");
if (y.style.display === 'none') {
y.style.display = 'block';
} else {
y.style.display = 'none';
}
}
I thought that just changing the div id's to div classes, and the #imagenumber's to .imagenumber's (in addition to the change in the javascript I described above) would work but the script stops working when I do. I need the script to function in the same way that the code I am pasting below does, but with div classes instead of div Id's. Please tell me where I am going wrong.
CSS:
#firstimage {
width: 100px;
height: 100px;
padding: 0px 0;
text-align: center;
background-color: green;
margin-top:20px;
color: white;
}
#secondimage {
width: 100px;
height: 100px;
padding: 0px 0;
text-align: center;
background-color: blue;
margin-top:20px;
color: white;
}
#thirdimage {
width: 100px;
height: 100px;
padding: 0px 0;
text-align: center;
background-color: red;
margin-top:20px;
color: white;
}
HTML:
<button onclick="myFunction()">Try me</button>
<div id="firstimage">
DIV element.
</div>
<div id="secondimage">
A second DIV element.
</div>
<div id="thirdimage">
A third DIV element.
</div>
Javascript:
function myFunction() {
var x = document.getElementById("firstimage");
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
var y = document.getElementById("secondimage");
if (y.style.display === 'none') {
y.style.display = 'block';
} else {
y.style.display = 'none';
}
}
document.getElementsByClassName returns an array of elements, so you would need to iterate through that array and operate on each element within that loop.
You should use getElementsByClassName() or querySelectorAll() to collect all div.Klass (Klass being an arbitrary name). The following Snippet uses querySelectorAll() details are commented in source.
SNIPPET
function toggleDiv() {
// Collect all .image into a NodeList
var xs = document.querySelectorAll(".image");
// Declare i and qty for "for" loop
var i, qty = xs.length;
// Use "for" loop to iterate through NodeList
for (i = 0; i < qty; i++) {
// If this div.image at index [i] is "none"...
if (xs[i].style.display === 'none') {
// then make it "block"...
xs[i].style.display = 'block';
} else {
// otherwise set display to "none"
xs[i].style.display = 'none';
}
}
}
#firstimage {
width: 100px;
height: 100px;
padding: 0px 0;
text-align: center;
background-color: green;
margin-top: 20px;
color: white;
}
#secondimage {
width: 100px;
height: 100px;
padding: 0px 0;
text-align: center;
background-color: blue;
margin-top: 20px;
color: white;
}
#thirdimage {
width: 100px;
height: 100px;
padding: 0px 0;
text-align: center;
background-color: red;
margin-top: 20px;
color: white;
}
<button onclick="toggleDiv()">Try me</button>
<div id="firstimage" class='image'>
DIV element.
</div>
<div id="secondimage" class='image'>
A second DIV element.
</div>
<div id="thirdimage" class='img'>
A third DIV element.
</div>
In this function, just using an "array-like" object such as a NodeList demonstrated in the Snippet above. An array would be used in the same manner as it is in the Snippet. Should you want to do more advanced processing of the divs such as running a function on each of them and returned then converting an "array-like" object into an array would be necessary to run methods like map, forEach, slice, etc.
I'm confused why the onclick function doesn't register the first time it is clicked. Each div with the onclick trigger has to be clicked twice the first time.
function selected(elmnt) {
if (elmnt.style.backgroundColor == "transparent")
elmnt.style.backgroundColor = "#990000"
else
elmnt.style.backgroundColor = "transparent"
}
#container {
background-color: transparent;
height: 100px;
width: 100px;
}
<div id="container" onclick="selected(this)">click me</div>
Am I missing something here?
It is because your element style is not transparent. Only your element's computedStyle is. Try this:
function selected(elmnt) {
if (elmnt.style.backgroundColor == "transparent")
elmnt.style.backgroundColor = "#990000"
else
elmnt.style.backgroundColor = "transparent"
}
#container {
background-color: transparent;
height: 100px;
width: 100px;
}
<div id="container" onclick="selected(this)" style="background-color: transparent;">click me</div>
There's also the natural way:
function selected(elmnt) {
if (elmnt.style.backgroundColor == "")
elmnt.style.backgroundColor = "#990000"
else
elmnt.style.backgroundColor = ""
}
#container {
background-color: transparent;
height: 100px;
width: 100px;
}
<div id="container" onclick="selected(this)">click me</div>
The element doesn't start with a background-color of transparent so it always goes to the else. Changing the div to
<div id="container" onclick="selected(this)" style='background-color:transparent'>www</div>
will make it work. A css style sheet doesnt' append style to the DOM elements physically.
Both answers above absolutely agree initially style is not set.
Just to tell you for next time how to DEBUG it
us console.log() click F12 for developer tools then console tab
I am fan of short IFs when simple IF
<script>
function selected(elmnt) {
console.log(elmnt.style.backgroundColor)
var bG= elmnt.style.backgroundColor
elmnt.style.backgroundColor = ( bG == '' || bG == "transparent") ? "#990000" : "transparent";
}
</script>