简体   繁体   中英

Input boxes that expand onClick with jQuery

I have this input[type="text"] on my page on which I've been working on for some time. What I wanna do is to create an effect of it expanding, when the user clicks in it. Also, I want it to return to its normal width when the mouse goes out.

My code so far:

 $(document).ready(function() { $("input").click(function() { var i; for (i = 250; i < 501; i++) { $(this).css("width", (i.toString + "px")) } }) }) 
 input[type="text"] { background-color: #000; color: #fff; border-radius: 10px; border-style: none; height: 50px; width: 250px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text"> 

I've used the .click() jQuery function here. Are there any other functions which can detect a cursor in an element? Something like .cursorIn() , if it exists.

You can use transition: width ease 1s (and use the :hover psuedo element if you want)

See demo below:

 $(document).ready(function() { $("input").click(function() { $(this).css("width", "500px") }) }) 
 input[type="text"] { background-color: #000; color: #fff; border-radius: 10px; border-style: none; height: 50px; width: 250px; transition: width ease 1s; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text"> 

With pure CSS you can use the focus psuedo element like this:

 input[type="text"] { background-color: #000; color: #fff; border-radius: 10px; border-style: none; height: 50px; width: 250px; transition: width ease 1s; } input[type="text"]:focus { width : 500px; } 
 <input type="text"> 

There is CSS solution to it, using transition with toggling class .on("click") : fiddle

CSS

input[type="text"] {
  background-color: #000;
  color: #fff;
  border-radius: 10px;
  border-style: none;
  height: 50px;
  width: 250px;
  transition: width .3s linear;
  -webkit-transition: width .3s linear;
}
.expand {
  width:500px;
}

HTML

<input type="text" />

jQuery

$("input[type='text']").on("click", function(e){
  $(this).toggleClass("expand");
}

You can use mouseenter or hover

 //Mouseenter
 $(document).ready(function() {
  $("input").on("mouseenter",function() {
    var i;
    for (i = 250; i < 501; i++) {
      $(this).css("width", (i.toString + "px"))
    }
  });
 });


 //Hover
 $(document).ready(function() {
      $("input").hover(function() {
        var i;
        for (i = 250; i < 501; i++) {
          $(this).css("width", (i.toString + "px"))
        }
    });
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM