Search code examples
javascriptjquerycsscolorbox

Continuous rotate image onclick of button


To display Image I used colorbox..In that I have add rotate-left and rotate-right to rotate the image.. The code is:

var rotate_right = document.getElementById('cboxRight');
$(rotate_right).on('click', function () {
    var cboxphoto = document.getElementsByClassName('cboxPhoto')[0].style;
    cboxphoto.setAttribute('-ms-transform', 'rotate(90deg)');
});

var rotate_left = document.getElementById('cboxLeft');
$(rotate_left).on('click', function () {
    var cboxphoto = document.getElementsByClassName('cboxPhoto')[0].style;
    cboxphoto.setAttribute('-ms-transform', 'rotate(270deg)');
});

It rotate 90deg if I click again on rightrotate button then it wont work..I want to rotate it again when click on button


Solution

  • You're only ever rotating to 90 or 270 degrees. When you click again, it doesn't move as it is already rotated to that angle.

    Keep track of the current rotation instead and set the attribute to that value plus or minus 90deg - you can probably clean up the code a bit as well, but something like this fiddle: http://jsfiddle.net/w6ho689e/

        var degrees = 0;
    $("#cboxRight").on('click', function () {
        var $cboxphoto = $('.cboxPhoto');
        degrees += 90;
        $cboxphoto.css('-ms-transform', 'rotate(' + degrees + 'deg)');
        $cboxphoto.css('-webkit-transform', 'rotate(' + degrees + 'deg)');
        $cboxphoto.css('transform', 'rotate(' + degrees + 'deg)');
    });
    
    $("#cboxLeft").on('click', function () {
        var $cboxphoto = $('.cboxPhoto');
        degrees -= 90;
        $cboxphoto.css('-ms-transform', 'rotate(' + degrees + 'deg)');
        $cboxphoto.css('-webkit-transform', 'rotate(' + degrees + 'deg)');
        $cboxphoto.css('transform', 'rotate(' + degrees + 'deg)');
    });