Indrek Hints
Indrek Hints

Reputation: 1

div width changing function

Can someone tell me why the function does not accept the first value if I want to change the div from input in real time. Also, the function does not activate the reducing the input value ec 400px to100px. Works well from entering second parameter. If enter 244, div change only to 44px. If entering space after that it go to 244 which is correct. But it is not UX correct. Need only javascript solution for this. Thanks

<!DOCTYPE html>
<html>
<head>
	<title>gr</title>
    <style>#in{
	border:1px solid grey;
	height: 200px;
	width: 100%;
	transition: all 1s;
     }
     </style>
</head>
<body>

   <div id='in'></div>
   	<input  type="text" id='sisse' onkeypress="change()">
 <script>
     function change(){
  	   document.getElementById('in').style.width=document.getElementById('sisse').value+'px'
     }
  	
  </script>
</body>
</html>

Upvotes: 0

Views: 51

Answers (2)

SyncroIT
SyncroIT

Reputation: 1568

You should use onchange event. Inside the function parameters you can pass the element that's firing the event, in this case, it will be the input, so you can do this:

<input  type="text" id='sisse' onchange="change(this)">
<script>
     function change(el) {
         document.getElementById('in').style.width=el.value+'px'
     }
</script>

The reason because you should not use onkeypress is because this event fires before the input is updated, so when reading the input value you will not get the updated one. Instead, onchanges fires everytime that the input is updated.

Upvotes: 0

You need to change onkeypress to onkeyup

The onkeypress event is not fired for all keys (e.g. ALT, CTRL, SHIFT, ESC, BACKSPAC ...) in all browsers. To detect only whether the user has pressed a key, use onkeydown or keyip instead, because it works for all keys.

The keypress event is fired when a key is pressed down and that key normally produces a character value

function change(){
  	   document.getElementById('in').style.width=document.getElementById('sisse').value+'px'
     }
#in{
	border:1px solid grey;
	height: 200px;
	width: 100%;
	transition: all 1s;
 }
<div id='in'></div>
<input  type="text" id='sisse' onkeyup="change()">

Upvotes: 2

Related Questions