0

I am rotating an "E" to make an eye test, so when the user clicks the directional button the "E" will rotate. My problem is that the "E" changes location after the initial click. I need it to stay in the same position. Here is a GIF of the occurrence:

EMove

My styling:

div.container4 p {
        margin: 0;
        position: absolute;
        top: 50%;
        left: 50%;
        margin-right: -50%;
        transform: translate(-50%, -50%);
        font-size: 2em;
        font-family: Arial, Helvetica, sans-serif;            
    }

Code:

<div class="container4" style="height:inherit;">
<p id="E">E</p>
</div>

JavaScript:

rotateE: function () {
    var step = Math.floor((Math.random() * 4) + 1);
    switch (step) {
        case 1:
            $('#E').css({ 'transform': 'rotate(' + 90 + 'deg)' })                
            break;
        case 2:                
            $('#E').css({ 'transform': 'rotate(' + 180 + 'deg)' })
            break;
        case 3:                
            $('#E').css({ 'transform': 'rotate(' + 270 + 'deg)' })
            break;      
        case 4:
            $('#E').css({ 'transform': 'rotate(' + 360 + 'deg)' })
            break;      
        default:

    }
}

Something I did notice in dev tools was that the transform: translate(-50%, -50%); gets cancelled out after the first click:

css

Thank you for any help to correct this.

Cleaven
  • 974
  • 2
  • 9
  • 30
  • 2
    You need to combine the `translate(-50%, -50%)` with the `rotate` other wise it will be overwritten eg. `$('#E').css({ 'transform': 'translate(-50%, -50%) rotate(' + 90 + 'deg)' })` – Turnip Jan 29 '19 at 12:55
  • @Turnip Thank you I have used this and it works, should have posted an answer :) – Cleaven Jan 29 '19 at 13:04
  • @Turnip Do you by any chance know how I can determine which direction or rotation the "E" is in when the click happens, in Javascript? – Cleaven Jan 29 '19 at 13:06
  • Read this: https://css-tricks.com/get-value-of-css-rotation-through-javascript/ and also this: https://stackoverflow.com/questions/42267189/how-to-get-value-translatex-by-javascript – Turnip Jan 29 '19 at 13:16
  • Thank you very much, that helped a lot! – Cleaven Jan 29 '19 at 14:14

1 Answers1

1

The transform applied with javascript is overwriting the transform specified in CSS. Either add translate(-50%, -50%) to the JS transforms or change the styles to avoid using a transform. If you want to center the element you could always use flexbox instead of absolute positioning and transforms.

div.container4 {
    display: flex;
    justify-content: center;
    align-items: center;          
}
James Coyle
  • 9,922
  • 1
  • 40
  • 48