Wednesday, July 18, 2012

Resize images proportionally keeping the aspect ratio

Here is the solution with jQuery -
Fiddle Demo: http://jsfiddle.net/dipaks2011/3yfgk/

CSS //to center and vertically middle align the image
div{ 
    width: 140px; 
    height: 140px; 
    border: 1px solid #f00; 
    text-align: center; 
    vertical-align: middle; 
    display: table-cell;
}
Note: display: table-cell; supports IE8+

HTML
<div>
    <img src="http://www.htmlgoodies.com/img/2010/11/jquery.jpg" />
</div>
jQuery
<script type="text/javascript">
    $(function(){
        var max_size = 130;
        $("div img").each(function() {
            if ($(this).height() > $(this).width()) {
                var h = max_size;
                var w = Math.ceil($(this).width() / $(this).height() * max_size); 
            }
           else{
               var w = max_size;
               var h = Math.ceil($(this).height() / $(this).width() * max_size);
           }
           $(this).css({'height': h, 'width': w});
        });
    });
</script>


Thursday, July 12, 2012

Styling input type file

Styling input type file is not very easy and most of the developers have stopped putting on efforts saying it can't be done!

Well, with CSS opacity and z-index we can style the file input which will work in IE7 and IE8 too. Here is how -

Fiddle Demo: http://jsfiddle.net/dipaks2011/2JJsH/14/

HTML
<div class="styleFileInput">       
  <input type="text" class="browseText" /> //will work as file text field
  <input type="button" value="Browse" class="browseButton" /> // will work as browse button
  <input type="file" size="1" class="theFileInput" /> // Actual input type file which has opacity: 0
</div>

CSS
.styleFileInput{
    position: relative;
}
.browseButton{
    border: 1px solid #b1902c;
    font-size: 0.9em;
    color: #fff;
    padding: 3px 8px;
    border-radius: 4px;
    background: #a7851c;
}
.browseText{
    width: 150px;
    margin: 0 48px 0 0;
    padding: 2px 0;
}
input.theFileInput{
    position:absolute;
    top:0px;
    left: 156px;   
    opacity:0;
    -moz-opacity:0;
    filter:alpha(opacity:0);
    z-index:2;
    width:80px;
    font-size: 1em;
}

jQuery 
$('input[type="text"]').keypress(function(e){
    e.preventDefault();    
});
 
$('.theFileInput').change(function(){
    $('.browseText').val($(this).val());
});

// if condition for Webkit and IE
if($.browser.webkit || $.browser.msie){
    $('.theFileInput').css('left', '190px');
}


Fiddle Demo: http://jsfiddle.net/dipaks2011/2JJsH/14/