ktewes
(Kalle)
May 14, 2020, 9:49am
1
Hi all,
this is driving me nuts…
The button is supposed either to make the square invisible or visible
The function ‘visibility’ gets its target from the button´s/element´s dataset (data-mytarget)
The function ‘visibility’ works, but not on the first click (though the console shows the target element incl. it´s display-status on the first click)
From the second click forward it works perfectly…
Where´s my mistake…?
Thanks in advance, Kalle
display.zip (14.6 KB)
h_classen
(Hans-Gerd Claßen)
May 14, 2020, 10:37am
2
on first run it does not own the style display
so may be:
if (!myElement.style.display || myElement.style.display === 'block')
… or any better logic would work
have a best day!
Hans
3 Likes
MarkHunte
(Mark Hunte)
May 14, 2020, 10:40am
3
Beat me to it…
But on a whim cos this has caught me out in the past, I thought there must be a way to get the ( in my thinking) the inherited display value.
What I came up with was actually the computed value, which is after the styles are set.
var myElement = document.querySelector ('.'+element.dataset.mytarget);
let compStyles = window.getComputedStyle(myElement);
//console.log (compStyles.display);
console.log ('display = ' + compStyles.display);
if (compStyles.display == 'block' ) {
myElement.style.display = 'none';
} else {
myElement.style.display = 'block';
}
1 Like
ktewes
(Kalle)
May 14, 2020, 11:03am
4
Ok my friends, both methods work perfectly. Thanks a lot for that. And I think, I´ve understood the underlying problem. Though - quite confusing at first
MaxZieb
(Loves Hype)
May 14, 2020, 11:57am
5
You can also just inverse the logic in such cases (test for the fail case first):
if (myElement.style.display == 'none') {
myElement.style.display = 'block';
} else {
myElement.style.display = 'none';
}
written in one line
myElement.style.display = myElement.style.display=='none'? 'block':'none';
2 Likes
MaxZieb
(Loves Hype)
May 14, 2020, 12:03pm
6
PS: That works because your testing against a boolean outcome and the fail case of undefined
is also counted as false in JavaScript. Hence, the browser (or Hype) sets the attribute if the element isn’t visible to start with, so we can test against that. Everything else leads to being displayed.
1 Like