I'm currently working on a project where I have to have a textarea element with an id of editor that updates a div element with an id of preview with its value as the user types into it. Currently, the preview element only updates with the text once the user stops focusing on the editor element, however, I want it to update immediately as the user types. I know this would be easy to achieve in React but is there a way to do it in plain JavaScript? This is the code I have so far:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Markdown Previewer</title>
</head>
<body>
<div id="content">
<textarea id="editor">
</textarea>
<div id="preview">
</div>
</div>
</body>
</html>
JAVASCRIPT
const preview = document.getElementById('preview');
const editor = document.getElementById('editor');
editor.addEventListener('change', (event) => {
console.log(event);
preview.textContent = event.target.value;
})
Any help appreciated.
Change the event to input instead of change. input is triggered every time the value of an element changes even while it still is in focus. change event on the other hand will be triggered when an element is changed and then loses focus.
Read more: https://html.com/attributes/textarea-onchange/#ixzz7AsNuUXNU
const preview = document.getElementById('preview');
const editor = document.getElementById('editor');
editor.addEventListener('input', (event) => {
console.log(event);
preview.textContent = event.target.value;
})
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Markdown Previewer</title>
</head>
<body>
<div id="content">
<textarea id="editor">
</textarea>
<div id="preview">
</div>
</div>
</body>
</html>
this is working code, You need to put your javascript after the html code, javascript is scripting language whaich means it executes line by line so if you put it before preview and editor element then you are trying to access them before there are initialized, and it wont work, when you put javascript code after html code then code will work as textarea element is already initialized and availbale to use
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0"
<title>Markdown Previewer</title>
</head>
<body>
<div id="content">
<textarea id="editor">
</textarea>
<div id="preview">
</div>
</div>
<script>
console.log('yes')
const preview = document.getElementById('preview');
const editor = document.getElementById('editor');
editor.addEventListener('change', (event) = > {
preview.textContent = event.target.value;
})
</script>
</body>
</html>