Hey guys, I've made a simple JavaScript toggle, but I got struck on how to make a button fire the function every time when you click on it. I don't know how to explain this. But take a look at the code and tell me how to achieve the result I want. ('In case you were lazy to write from scratch, the code is full functioning') <!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> Code (markup): Thank you,
Do you mean something like this? http://jsfiddle.net/tZPg4/16861/ or http://jsfiddle.net/mlotfi/43gyzepo/ It's in jquery though.
Thank you, Not quite. I mean I want to do like the one on twitter menu. Take a look and try it. Many web sites has this feature. If I can't make it myself I have to borrow from someone. I don't use jQuery for a long time I almost forgot everything about it.
Not sure what do you want to achieve but you can simply disable the button make it not fired; with b.disabled = true; and b.disabled = false; to enable it again. I assume you want : <!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'; b.disabled = true; }); d[0].addEventListener('mouseup', (e) => { e.stopPropagation(); }); window.addEventListener('mouseup', () => { d[0].style.display = 'none'; b.disabled = false; }); </script> </body></html> HTML:
Nothing different result produced. I'll put this aside for a while. I've asked a guy who help developed Firefox, even an engineer at that talent level cannot help me on this.
Hi. It (post #1) surely toggles but only with <enter> or <space> key at the button. Not with mouse-click, because of the last part: window.addEventListener('mouseup', () => { d[0].style.display = 'none'; }); Code (JavaScript): Hmm, strange looking code man. I didn't know we could replace function(){} Code (JavaScript): with this syntax: () => {} Code (JavaScript):
twitter has lots of buttons to press. are you just trying to show an input field and hide it? Where does the complexity come in?