Kārlis Janisels Kārlis Janisels - 15 days ago 6
CSS Question

How to change image css after rotating it in JS?

There is nice css trick to always position image in the center of div regardless of image size or aspect ratio.

<style>
.img_wrap {
padding-bottom: 56.25%;
width: 100%;
position: relative;
overflow: hidden;
}
#imgpreview {
display: block;
max-height: 100%;
max-width: 100%;
width: auto;
height: auto;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
</style>
<div class="img_wrap">
<img id="imgpreview" src="http://i.imgur.com/RRUe0Mo.png" alt="your image" />
</div>


Then I added jquery code for rotating image

$(document).ready(function(){
var rotation = 0;

jQuery.fn.rotate = function(degrees) {
$(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
'-moz-transform' : 'rotate('+ degrees +'deg)',
'-ms-transform' : 'rotate('+ degrees +'deg)',
'transform' : 'rotate('+ degrees +'deg)'});
};

$('#imgpreview').click(function() {
rotation += 90;
$(this).rotate(rotation);
// $(this).toggleClass("imgpreview");
});
});


However, when I am rotation image, it gets cropped. I want to avoid that.

I tried to play with addClass feature but with no success. If someone could suggest any solution would appreciate a lot.

I have created jsfidlle for this question.
Here the updated fiddle

Answer

You can achieve this with jquery by altering a little bit your code:

$('#imgpreview').click(function() {
    if (rotation === 360) {
        rotation = 0
    } else {
        rotation += 90;
    }
    $(this).rotate(rotation);
    if(rotation === 90 || rotation === 270) {
        $('.img_wrap').css('height', $(this).width());
    } else {
        $('.img_wrap').css('height', 'auto');
    }
});

There's maybe the need to alter your css also but it depends what is the end result that you wish to have.