Javascript – Expand input field width smoothly on click

csshtmljavascriptjquery

I want to display an input field .search when clicking on .icon class. I have managed to do that with following code. However instead of show/hide, I want to display the input field by smoothly expanding its width.

How that can be done?

JSFiddle Demo:

http://jsfiddle.net/9nPW9/

HTML:

<div class="box">
    <input class="search" type="search" placeholder="Search" />
     <div class="icon"></div>  
</div>

CSS:

.box{
    position: relative;
    width: 220px;
}

.search {    
    width: 200px;
    padding: 5px;
      -webkit-transition: all .5s ease;
    -moz-transition: all .5s ease;
    transition: all .5s ease;
    float: left;
}


.icon{
    width: 20px;
    height: 20px;
    background: red; 
    position: absolute; 
    right: 0;
}

JS:

$('.icon').click(function() {
    $('.search').toggle();
});

Best Solution

Why not change your code to toggle a class, thus keeping a clear separation between functionality (JS) and style (CSS)

Below is some sample code, you will likely want to edit for your precise needs.

Demo Fiddle

JS

$('.icon').click(function() {
    $('.search').toggleClass('expanded');
});

CSS

 .box {
    position: relative;
    width: 220px;
}
.search {
    width: 200px;
    max-width:0;
    padding: 5px;
    transition: all .5s ease;
    position:absolute;
    right:20px;
    box-sizing:border-box;
    opacity:0;
}
.search.expanded {
    max-width:200px;
    opacity:1;
}
.icon {
    width: 20px;
    height: 20px;
    background: red;
    position: absolute;
    right: 0;
}