jessiebower
jessiebower

Reputation: 5

Can I make this media query work in my javascript?

i'm trying to get my site to know when it's above 1096 to execute some CSS styling, here is my code

var mq = window.matchMedia('@media all and (max-width: 1096px)');
if(mq.matches) {
    window.parent.document.getElementsByClassName("sticky-leaderboard-ad-container")[0].setAttribute("style","padding-top: 4rem !important; margin-left: 0 !important");
} 

please can someone let me know why this isn't working? thank you in advance

edit: i can't use CSS, it must be in javascript

Upvotes: 1

Views: 154

Answers (3)

Addis
Addis

Reputation: 2530

If you want to make your media respond when the screen size above 1096, you should instead use min-width: 1096px. max-width: 1096px captures when the screen is lower or equal to the target size.

if (window.matchMedia("(max-width: 1096px)").matches) {
  /* The viewport is less than, or equal to, 1096px pixels wide */
} else {
  /* The viewport is greater than 1096px pixels wide */
}

or:

if (window.matchMedia("(min-width: 1096px)").matches) {
  /* The viewport is greater than, or equal to, 1096px pixels wide */
} else {
  /* The viewport is less than 1096px pixels wide */
}

Besides window.parent.document.getElementsByClassName() doesn't make sense, change it to document.getElementsByClassName()

Upvotes: 1

soma
soma

Reputation: 101

You could create an event listener and make use of the window object to get the viewport dimensions.

window.innerWidth 
window.innerHeight
window.matchMedia("(min-width: 1096px)")

matchMedia docs

Upvotes: 0

Ricardo Rocha
Ricardo Rocha

Reputation: 16256

You don't need javascript to do that.

You can use only css media queries to accomplish the same behavior like this:

@media all and (max-width: 1096px)
.sticky-leaderboard-ad-container {
     padding-top: 4rem !important; 
     margin-left: 0 !important;
}

But, if you want to use javascript you can get the window width like this:

if(window.innerWidth < 1096) {
        let element = document.getElementsByClassName("sticky-leaderboard-ad-container")[0];
        element.setAttribute("style","padding-top: 4rem !important; margin-left: 0 !important");
} 

Upvotes: 1

Related Questions