Siyah
Siyah

Reputation: 2897

How to change position of input field when focused on?

I am trying to fix this, but I can't get it to work. I have made this JSFiddle to illustrate my problem:

https://jsfiddle.net/5rj2jtym/1/

<div class="wrapper">
   <p>Test header</p>
</div>

<input type="text" class="bla" onclick="changepos()" placeholder="put some text here" />

And the JS:

function changepos() {
    if(document.getElementsByClassName("bla")[0].style.top == '300px'){
        document.getElementsByClassName("bla")[0].style.top="0px";    
    }else{
        document.getElementsByClassName("bla")[0].style.top="300px";  
    }
}

What I want to achieve, is that the input field should take the place of the paragraph / header you can see in the fiddle. So when someone focuses / clicks on the input field, the input field should move up (preferably with an animation) so that we have a nice interaction. I tried it with JavaScript, but I can't get it to work.

Upvotes: 0

Views: 3811

Answers (2)

DubDJ
DubDJ

Reputation: 34

I'd definitely recommend the above CSS method, but just in case you want to use your original JavaScript method.

function changepos(input) {
  input.style.top = "0";
  input.style.transition = "all 0.8s";
}

function resetpos(input) {
  input.style.top = "300px";
  input.style.transition = "all 0.8s";
}
input {
  width: 100%;
  top: 300px;
  position: relative;
}
<div class="wrapper">

  <p>
    Test header
  </p>
</div>

<input type="text" class="bla" onfocus="changepos(this)" onblur="resetpos(this)" placeholder="put some text here" />

Upvotes: 2

Sysix
Sysix

Reputation: 1796

Why not use the css :focus Selector?

https://jsfiddle.net/5rj2jtym/12/

Upvotes: 1

Related Questions