Reputation: 3317
I made some js code for <div>
to appear or disappear.
[src.js]
openSearch = () => {
var con = document.getElementById("search-bar");
if(con.style.display == 'none') {
con.style.display = 'block';
} else {
con.style.display = 'none';
}
}
[style.css]
#search-bar {
position: absolute;
height: 4em;
width: 20em;
background-color: white;
border: 1px solid black;
padding: 1.5rem;
right: 0;
display: none;
}
and add onclick="openSearch()"
to <a>
tag.
When I click the <a>
tag first time, it doesn't work anything.
But click again, it works properly.
So I tried to console.log(document.getElementById("search-bar").style.display, it throws ""(blank).
I wonder that I defined display: none
to search-bar
but why initial style.display of search-bar
is blank value?
And how can I fix it?
Upvotes: 3
Views: 11355
Reputation: 12959
Use this line code:
if(con.style.display == 'none' || con.style.display == '') {
openSearch = () => {
var con = document.getElementById("search-bar");
if(con.style.display == 'none' || con.style.display == '') {
con.style.display = 'block';
} else {
con.style.display = 'none';
}
}
#search-bar {
position: absolute;
height: 4em;
width: 20em;
background-color: white;
border: 1px solid black;
padding: 1.5rem;
right: 0;
display: none;
}
<div id="search-bar">My Div</div>
<a onclick="openSearch()" href="#">Click</a>
Upvotes: 0
Reputation: 5895
when you set the display:none
in css it innisial like display=""
. and not display=none
. the result is the same, but if you check display='none'
he will return false.. you can try it like this:
openSearch = () => {
var con = document.getElementById("search-bar");
if(con.style.display == '') {
con.style.display = 'block';
} else {
con.style.display = '';
}
}
and it will work fine
Upvotes: 0
Reputation: 3317
[SOLVED]
First I add display: none
to css file.
But after style="display: none"
to a tag, it works properly.
Maybe I think there is loading priority, But I don't know why exactly.
Upvotes: 1
Reputation: 28455
Alternatively, you can move the display style to another class and can toggle class.
openSearch = () => {
var con = document.getElementById("search-bar");
con.classList.toggle("hidden");
}
#search-bar {
position: absolute;
height: 4em;
width: 20em;
background-color: white;
border: 1px solid black;
padding: 1.5rem;
right: 0;
}
.hidden {
display: none;
}
<a onclick="openSearch()">Toggle</a>
<div id="search-bar" class="hidden">Some text here</div>
Upvotes: 3
Reputation: 50
function openSearch()
{
var div = document.getElementById("search-bar");
if (div.style.display !== "none") {
div.style.display = "none";
}
else {
div.style.display = "block";
}
}
Upvotes: 1
Reputation: 77
You could try initializing the style via js to none:
document.getElementById("search-bar").style.display = 'none';
When the page loads. My guess is that'll work.
Upvotes: 0