Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript DOM Manipulation: Why Isn’t It Working?

Struggling with JavaScript DOM manipulation? Learn why your keypress event isn’t updating font size and how to fix common mistakes with event listeners.
Frustrated developer looking at JavaScript code error with font size not updating on keypress in DOM manipulation tutorial Frustrated developer looking at JavaScript code error with font size not updating on keypress in DOM manipulation tutorial
  • ⚠️ The keypress event is outdated and doesn't work well in modern browsers. Use keydown or keyup instead.
  • 📦 DOM changes often fail because of wrong selectors that return null.
  • 🔍 Keyboard layout differences can make key values like '+' not work right unless you handle them properly.
  • 📐 You need to keep track of font size changes to make sure they update steadily.
  • 🛠 DevTools and computed styles are key for checking live DOM and CSS changes.

Are you having trouble with a JavaScript keypress event that won’t update your DOM's font size? Lots of people do. You might be building new interactive features or just trying to fix your code when it doesn't work. Problems with JavaScript DOM changes, especially when changing font size, are very common. Let's look at the main reasons why your event might not be running or your styles aren't changing, and how to fix them.


How Keypress Events Work in JavaScript

In JavaScript, responding to keyboard input is a common way to create user interactions. This is helpful for things like accessibility features, hotkeys, and changing styles. The keypress event used to do this, but it is now outdated and you should not use it in new projects.

Instead, you should use the keydown or keyup events. Each has its own behavior:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • keydown: This runs when you first press a key. It's good for immediate reactions, like changing styles.
  • keyup: This runs when you let go of a key. It's good for things that should happen after you finish typing.

Here’s a simple example using keydown to see key presses:

document.addEventListener('keydown', function(e) {
  console.log('Key pressed:', e.key);
});

Why avoid keypress? MDN says this:

💡 According to MDN, do not use keypress in new code. It will not work well across modern browsers.

Using keydown works better with more browsers and more reliably across devices and different ways people type.


Common Mistake 1: Getting the key Property Wrong

One common reason for problems when using keyboard events is misunderstanding the key property. This property gives back a string that shows the key a user pressed. But the exact string can change based on the keyboard layout and if keys like Shift or Alt are pressed.

For example:

if (e.key === '+') {
  // This should increase font size
}

This check might not work on all keyboards. On many layouts, you need to hold down the Shift key to get the + symbol. And even then, it might give you = or another character.

To make sure it works the same way everywhere, think about handling many possible keys. And think about differences in keyboard layouts:

switch (e.key) {
  case '+':
  case '=': // Some layouts make '+' equal to '='
    // Code to increase font size
    break;
  case '-':
    // Code to decrease font size
    break;
}

Or, you can use e.code. This gives you a physical key ID (like Equal, Minus, ArrowUp, etc.). This means it works regardless of the keyboard layout. But know that e.code might not always match the exact character. You trade one thing for another here.


Common Mistake 2: Using querySelector Wrong

Another common mistake is using document.querySelector() to find a DOM element that isn't there. Or you might type the selector wrong, so it returns null.

Here's an example of something that fails quietly:

let target = document.querySelector('.non-existent-class');

This code won’t cause an error unless you try to do something with the target. But your code that changes the DOM will just fail without telling you.

To stop this, always check your selectors using browser DevTools or JavaScript:

document.addEventListener('DOMContentLoaded', () => {
  let target = document.querySelector('.text');
  console.log(target); // See if it's null
});

🧠 As MDN's guide to querySelector says, it only gives back the first element that matches or null.

Be sure the element is there before changing any styles.


Common Mistake 3: Event Listener Attached to the Wrong Element

When you work with keyboard actions, where you put your event listener matters. If you attach the listener to an element that is not in focus, or not even on the screen, the event might never run.

For example:

window.addEventListener('keydown', handler); // ✅ Works well throughout the app
document.body.addEventListener('keydown', handler); // ⚠️ Can fail if body is not in focus

Most times, it's safest to attach the listener to document or window. This is true especially when you want to change styles everywhere on the page, like changing font size for the whole page.

And remember, elements like inputs and buttons can "trap" focus. They can stop keyboard events from reaching other parts. So, unless you have a reason to use form controls, attach your listener to higher-level parts of your page.


Finding the Problem: Step-by-Step

When a keyboard event does not run or style changes don't happen, use these steps to find the problem:

  1. Check if JavaScript runs after the DOM loads: Put <script defer> in your HTML or use DOMContentLoaded.

    document.addEventListener('DOMContentLoaded', function() {
      // You can safely change the DOM here
    });
    
  2. Check if your DOM selector finds an element. Use console.log() to see what comes back.

    const target = document.querySelector('.text');
    console.log(target); // If it's null, it didn’t find the element
    
  3. Make sure your event listener is running. Log the key event to see the key value:

    document.addEventListener('keydown', (e) => {
      console.log('Key:', e.key);
    });
    
  4. Look for mistakes in your code or errors while it runs. Use your browser’s developer console (F12 on most browsers). Red icons or error messages will show you where your code stopped working.

These simple tips often help you find why things are not working faster.


Making Font Size Update

To update font size JavaScript based on user key input, you need to keep track of the font size as a number that can change. If you don't do this, the font size often updates only once, or not at all.

Here’s how to do it correctly:

let fontSize = 16;

document.addEventListener('keydown', (e) => {
  if (e.key === '+') {
    fontSize += 2;
  } else if (e.key === '-') {
    fontSize = Math.max(10, fontSize - 2); // Stops it from getting too small
  }

  document.body.style.fontSize = fontSize + 'px';
});

This code sets up a system that keeps track of the font size as it responds to key presses. And it makes sure the font size doesn't get too small, so text stays easy to read and use.

You can use parseInt with window.getComputedStyle() if you want to figure out the font size from the style that's currently on the page:

let current = parseInt(window.getComputedStyle(document.body).fontSize);

Fixing Typos and Code Errors

JavaScript is picky about small code problems. These can appear without you knowing:

  • Use === instead of = when you compare things.

  • Be careful with quote marks:

    e.key == ‘+’  // ❌ Wrong quote marks (curly quotes)
    e.key === '+' // ✅ Correct
    
  • Correct property names are important. Setting document.body.style.font-size = '18px' will not work. It must be camelCase:

    document.body.style.fontSize = '18px';
    

Use tools like ESLint or code editors that check for problems. They can help you find these mistakes fast.


Good Ways to Use Event Listeners

Handling keyboard events the right way helps make sure your app works well and fast. Do these things:

  • ✅ Use addEventListener only when you need to. And take it away with removeEventListener when you are done to stop memory problems.
  • ✅ Put listeners at the highest place you can, like on document or window.
  • ✅ Use throttling or debouncing to stop slowdowns if someone holds down a key.

Here's an example of debouncing a key event that happens often:

function debounce(func, delay) {
  let timeout;
  return function(...args) {
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(this, args), delay);
  };
}
document.addEventListener('keydown', debounce((e) => {
  // Do something here
}, 300));

Checking CSS Changes with JavaScript

You might think your styles are working, but just looking at it doesn't always show if it worked. To check that your DOM changes have happened, look at the styles with code:

let computedSize = window.getComputedStyle(document.body).fontSize;
console.log('Current font size:', computedSize);

You can see this in your browser's console. Or you can use it to update other parts of your app if needed.

This is very helpful when changing styles based on what a user does. And it helps you be sure that your JavaScript DOM manipulation is working right.


Making Things Accessible

Changing font size with the keyboard can make things much more accessible for people who have trouble seeing. Doing these good things helps make sure your interactive parts work for everyone:

  • Don't set strict upper limits on font sizes.
  • Use clear, accessible buttons (with ARIA labels) along with keyboard actions.

Example:

<button aria-label="Increase font size" onclick="increaseFont()">A+</button>
<button aria-label="Decrease font size" onclick="decreaseFont()">A-</button>

This lets users click with a mouse or use a screen reader, besides using the keyboard.


Using Web Dev Tools to Help Find Problems

New DevTools are very helpful for checking if JavaScript DOM updates are working right. Important features include:

  • Elements panel: Look at live HTML and CSS.
  • Console tab: See messages and find errors.
  • Sources tab: Put breaks in your code to pause it and look at variables.
  • Computed styles: Check if style changes like font-size are going onto elements.

According to Google Chrome Developers, learning to use DevTools well makes finding problems much faster. And it gives you fine control over how to use JavaScript with keypress events.


Make a Helper Function for Font Size Changes

To make your code for changing font size cleaner and something you can use again, make a helper function. Put all the code for adjusting the size in it:

function adjustFontSize(change) {
  const currentSize = parseInt(window.getComputedStyle(document.body).fontSize, 10);
  document.body.style.fontSize = (currentSize + change) + 'px';
}

document.addEventListener('keydown', (e) => {
  if (e.key === '+' || e.key === '=') adjustFontSize(2);
  if (e.key === '-') adjustFontSize(-2);
});

When you separate code into helper functions like this, it makes your code easier to manage and check.


Quick Look Back and Last Thoughts

To sum up, working with a keypress event JavaScript situation to update font size can be hard, especially if you are new to JavaScript DOM manipulation. But most problems come from just a few mistakes that happen often:

  • Attaching to the wrong element.
  • Getting the key property wrong or using it badly.
  • Picking DOM elements that aren't there.
  • Not keeping track of the font size when you change it.

With clean code, good use of browser tools, and good debugging tools, you can build apps that work well, are easy to use, and respond to the keyboard. Keep trying things, keep checking, and know this: even small DOM changes need care.


Citations

Mozilla Developer Network. (n.d.). KeyboardEvent.key – Web APIs | MDN. Retrieved from https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key

Mozilla Developer Network. (n.d.). Element.querySelector(). Retrieved from https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelector

Mozilla Developer Network. (n.d.). Document: DOMContentLoaded event. Retrieved from https://developer.mozilla.org/en-US/docs/Web/API/Document/DOMContentLoaded_event

Google Chrome Developers. (n.d.). Debugging JavaScript. Retrieved from https://developer.chrome.com/docs/devtools/javascript/

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading