Reputation: 404
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
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