MWR
MWR

Reputation: 404

Javascript Media Query bug, it won't apply the code if the window is equal or smaller than "x" pixels, only on resize

So, I don't know whether something is missing from this script, or it's a bug, but..

I have a h1, if the window width is smaller than 350px, I want to change the innerHTML. Pretty basic, huh?

When the screen size is already smaller than 350px the script won't work! What can I do?

HTML

<h1 id="h1">Text</h1>

javascript

var h1 = document.getElementById("h1");
var mediaQuery = window.matchMedia('(max-width: 350px)');

function h1Text(){
 if(mediaQuery.matches){
   h1.innerHTML = ("Text 1");
  }
 else {
   h1.innerHTML = ("Text");
    }
  }

mediaQuery.addListener(h1Text);


 //Resize the document and make it smaller than 350px, then run again the fiddle

The fiddle: https://jsfiddle.net/euy005gk/6/

Upvotes: 0

Views: 30

Answers (1)

M&#225;t&#233; Safranka
M&#225;t&#233; Safranka

Reputation: 4106

Just call h1Text manually after you set it as the listener.

mediaQuery.addListener(h1Text);
h1Text();

As the name implies, .addListener() adds a function that will be called when the match state of the media query changes. It doesn't immediately execute the listener when you set it.

Upvotes: 1

Related Questions