JavaScript how do you make things events live (here's what I mean... | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

JavaScript how do you make things events live (here's what I mean...

J.S - There' s an input called x, and a p element t called par, I need the par.innerHTML = x.value; But x.value won't appear on par.innerHTML, unless I have onclick event and I click it. I want to know if there is a way to do this: When I type inside x (input), the value of x immediately prints on par.innerHTML (without having to click or anything). Example this code: https://code.sololearn.com/WT6VPR21WLh0/?ref=app

26th Jun 2019, 5:11 AM
Ginfio
Ginfio - avatar
5 Answers
+ 2
There is an event for that, it's the onkeydown event: element.onkeydown = ... or element.addEventListener("keydown", ...) If you just print out its value instantly, it will not print the key you actually pressed. To avoid this, you can use setTimeout. x.onkeydown = () => { setTimeout(() => { par.innerHTML = x.value; }, 0); }
26th Jun 2019, 5:16 AM
Airree
Airree - avatar
+ 1
If the element won't appeared, what's the purpose of adding onclick to an invisible element?
26th Jun 2019, 8:45 AM
Calviղ
Calviղ - avatar
+ 1
Calviղ , so when i click, it appears. what i mean is, the x value is not gonna appear on par while im typing. i wanted x.value to appear on par while im typing -instead of typing first, then i click the button, then x.value is on par. --
26th Jun 2019, 4:42 PM
Ginfio
Ginfio - avatar
0
Ginfio that's is not onclick event trigger, onclick event is for mouse click triggering, that's why I wondered element not appeared why would we needed onclick an invisible element. In your case, you can set input element with onmousedown or onpress events, it would be triggered rightly on the key pressed down.
27th Jun 2019, 5:33 AM
Calviղ
Calviղ - avatar