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>
		div { background: red; display: none; padding: 20px 10px; }
	<input type=button id=button value="Click Me" /><br/><br/>
		<input type=text placeholder="Type in here..." />
		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) => {
		window.addEventListener('mouseup', () => {
			d[0].style.display = 'none';

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.