0

I need to write a stylised font preview on the screen as a user types into a text box - like this (though I think this uses dated coding techniques): https://www.pet-tags.co.uk/engravingdetail?product=57&size=2

I can't find a specific example doing this - I found this question which is similar but doesn't write out the output to the screen: Best way to track onchange as-you-type in input type="text"?

I'd like to ensure this is done in a modern way with wide contemporary browser support (so excluding, say, IE8 is fine).

I can find no specific examples of this online.

Thanks.

niico
  • 11,206
  • 23
  • 78
  • 161

1 Answers1

1

You should use onInput event. I has quite a wide support: https://caniuse.com/#search=oninput.

Working example below:

const $source = document.querySelector('#source');
const $result = document.querySelector('#result');

$source.addEventListener('input', (e) => {
    $result.innerHTML = e.target.value;
})
<input id="source" />

<div id="result"></div>
extempl
  • 2,987
  • 1
  • 26
  • 38
  • I can't get this working. I've copied the above to an html file, wrapped the javascript in – niico Oct 26 '18 at 19:49
  • Have you tried it in a code snippet? I assume, you trying to access tags before they have rendered. Consider using `$(function () { })` wrapper for entire js code – extempl Oct 26 '18 at 19:51
  • It's not clear how this code snippet works - or how to make it work in an actual page – niico Oct 26 '18 at 19:58
  • @niico Use the wrapper or move `script` tag to the end of the `body` and it should work. – extempl Oct 26 '18 at 19:59
  • sorry which wrapper? You want me to put
    – niico Oct 26 '18 at 20:00
  • What is a 'code snippet'? I thought it was just the way of running code embedded on this site? How does this help me? (sorry I don't ask front end questions much) – niico Oct 26 '18 at 20:01
  • @niico Consider using `$(function () { })` wrapper for entire js code – extempl Oct 26 '18 at 20:01
  • 1
    @niico html file example: `
    `
    – extempl Oct 26 '18 at 20:03
  • That's exactly what I tried - except my div and input were *below* the script - so I guess the script needs to be below those?! – niico Oct 26 '18 at 21:10
  • @niico that's one of the approaches. The other one is `window.onLoad` or `$(function () {/* your code here */})` which I was trying to describe to you earlier. But this is a basics of front-end programming, which you lack. You should start to learn the basics. – extempl Oct 27 '18 at 03:56