0

Below I have this piece of JS code. When the resolution of the screen is between 995px and 1200px, then the css animation of transform: translate should be 22%. How can I do this?

CSS code:

.to_be_center {
        position: relative;
        transform: translate(-27%, 25%);
}

JS code:

function resolution() {
    width = window.screen.availWidth;

    if ((width>=995) && (width<1200)){
        document.getElementsByClassName("to_be_center").style.transform= "translateX(14%)"; 
    }
}

resolution();

I call the function in body - <body onload="resolution()">.

Daniel Beck
  • 20,653
  • 5
  • 38
  • 53
Santiya
  • 195
  • 3
  • 12
  • `` so that it is called on window resize. And for width refer this [Get the size of the screen, current web page and browser window](http://stackoverflow.com/questions/3437786/get-the-size-of-the-screen-current-web-page-and-browser-window) – Sagar Nov 17 '16 at 19:20
  • Thanks for the correction about body - the resolution is working when I test it with the Toogle Device Tool in Inspector, but I think the problem is in this line `document.getElementsByClassName("to_be_center").style.transform= "translateX(14%)";` – Santiya Nov 17 '16 at 19:32
  • document.getElementsByClassName('') returns an array. `document.getElementsByClassName()[0].style.transform ..` – Sagar Nov 17 '16 at 20:09

1 Answers1

1

Why not just use a CSS media query, and define for that screen size how .to_be_center should work?

@media (max-width: 995px) {
  .to_be_center{
    /*your styles here*/
  }
}

more info can be found here: https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries

Vinny
  • 449
  • 3
  • 6
  • Thank you, but I've already try many times with CSS media queries and didn't work. Also I read that the they didn't match with CSS animations, didn't know why and I headed to try with JS. – Santiya Nov 17 '16 at 19:15
  • is your css getting overwritten? did you check? can you post your css we can help with that – Sagar Nov 17 '16 at 19:22
  • `@media screen and (min-width: 995px) and (max-width: 1200px) { .to_be_center{ position: relative; transform: translate(-22%, 25%); /* background-color: red;*/ } }` When I try with the background-color works, but no with the animation . – Santiya Nov 17 '16 at 19:41
  • and the HTML code: ` Login ...` – Santiya Nov 17 '16 at 19:41
  • Yes, I have been overwritting it. Thank you for the observation! :) – Santiya Nov 17 '16 at 20:10