How to make the button work every time on click

Hi guys,

I’ve created this simple JavaScript toggle and I want it works every time when the button got clicked, as well as clicking somewhere else outside the target div area.

How to make it worked? Here’s what I have done so far:

<!DOCTYPE html>
<html><head>
	<style>
		div { background: red; display: none; padding: 20px 10px; }
	</style>
</head><body>
	<input type=button id=button value="Click Me" /><br/><br/>
	<div>
		<input type=text placeholder="Type in here..." />
	</div>
	<script>
		var d = document.getElementsByTagName('div')
		  , b = document.getElementById('button');
		
		b.addEventListener('click', () => {
			(d[0].style.display !== 'block') ? d[0].style.display = 'block' : d[0].style.display = 'none';
		});
		d[0].addEventListener('mouseup', (e) => {
			e.stopPropagation();
		});
		window.addEventListener('mouseup', () => {
			d[0].style.display = 'none';
		});
	</script>
</body></html>

When you remove window.addEventListener everything is working as expected.

Thank tou,

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.