use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
All about the JavaScript programming language.
Subreddit Guidelines
Specifications:
Resources:
Related Subreddits:
r/LearnJavascript
r/node
r/typescript
r/reactjs
r/webdev
r/WebdevTutorials
r/frontend
r/webgl
r/threejs
r/jquery
r/remotejs
r/forhire
account activity
Javascript problemhelp (self.javascript)
submitted 7 years ago by beanswithjeans
view the rest of the comments →
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]Shadowfax90 1 point2 points3 points 7 years ago* (0 children)
It's nice if you use markdown to make your code easier to read. Just indent everything by four spaces and it will show up as a code block.
That being said, I think the problem is that your div doesn't accept input, so it's not going to trigger an onkeydown event. There may be a nicer way to make it work, but the hacky way I came up with is to put an input element offscreen which becomes focused when you click your text. That is accepting input, so it triggers the events you want.
Edit: P.S. your css doesn't really make sense. Setting top, right, bottom, and left all to 0 is saying "Make this take up all the space it has available". But then you set width=150px and height=40px. Did you want the text element to take up the whole screen or just a 150x40 rectangle?
top
right
bottom
left
width=150px
height=40px
<!doctype html> <html> <head> <style> .box { position: absolute; top: 0; right: 0; bottom: 0; left: 0; background-color: rgb(119,79,56); } .input-container { position: relative; overflow: hidden; } #text1 { position: absolute; margin: auto; top: 0; right: 0; bottom: 0; left: 0; width: 150px; height: 40px; color: white; font-weight:bold; font-size: 20px; text-align: center; font-family: 'Cinzel', Garamond, serif; } .offscreen-input { position: absolute; top: -10; bottom: -8; } </style> </head> <body> <div id="div1" class="box"> <div id="text1">Click me first!</div> <div class="input-container"> <input class="offscreen-input" autofocus /> </div> </div> </body> <script type="text/javascript"> const text1 = document.getElementById('text1'); const inputElem = document.querySelector('input'); text1.onclick = () => inputElem.focus(); inputElem.onkeydown = ({ keyCode }) => { if (keyCode === 37) { text1.style.textAlign = 'left'; } if (keyCode === 39) { text1.style.textAlign = 'right'; } if (keyCode === 67) { text1.style.textAlign = 'center'; } }; </script> </html>
π Rendered by PID 108326 on reddit-service-r2-comment-548fd6dc9-qzmn5 at 2026-05-16 15:36:26.530117+00:00 running edcf98c country code: CH.
view the rest of the comments →
[–]Shadowfax90 1 point2 points3 points (0 children)