Passing target from element´s dataset

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 (14.6 KB)

on first run it does not own the style display

so may be:
if (! || === 'block')

… or any better logic would work :slight_smile:

have a best day!



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' ) { = 'none';
		} else { = 'block';
1 Like

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 :slight_smile:

You can also just inverse the logic in such cases (test for the fail case first):

if ( == 'none') { = 'block';	
} else { = 'none';

written in one line ='none'? 'block':'none';

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