1

I have an issue with window.matchMedia, in the below script I am trying to increment the numbers by 3 when the screen hits a max-width of 768px how ever that is not happening any advice?

<script>
var mq = window.matchMedia('@media (max-width:768px;)');
 mq.addListener(function(changed) {
  if(changed.matches) {
   var $x = document.getElementsByClassName("example");
    for(i=0; i < 40; i++){  
       $x[i].innerHTML = i+3;
    } 
   }else {
    $x[i].innerHTML = i+1;
   } 
});
</script>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
<style type="text/css">
@media (min-width:768px){
 body{background-color:#929292;}
</style>
</head>
<body>
<div class="example">1</div>
<div class="example">2</div>
<div class="example">3</div>
<div class="example">4</div>

</body>
</html>
  • why not do it in css? you have media queries there: [css media queries](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries) – Slava Shpitalny Mar 08 '16 at 21:59
  • It should be just `window.matchMedia('(max-width:768px;)');`, you don't need `@media` – adeneo Mar 08 '16 at 22:00
  • you can use the `:before` query and the method listed here: [prefix ordered list item numbers](http://stackoverflow.com/questions/5568229/how-can-i-prefix-ordered-list-item-numbers-with-a-static-string-using-css) – Slava Shpitalny Mar 08 '16 at 22:02

1 Answers1

0

Try it like this in the css (change the media query as you like) The 3 indicates the initial value

body {
    counter-reset: item 0;
    list-style-type: decimal;
}

.example:before {
    content: counter(item, decimal) ' ';
    counter-increment: item;
}

@media (max-width: 768px) {
    body {
        counter-reset: item 3;
    }
}

You can go here: jsfiddle and put the html:

<div class="example">a</div>
<div class="example">b</div>
<div class="example">c</div>
<div class="example">d</div>
<div class="example">e</div>

and the css:

body {
    counter-reset: item 0;
    list-style-type: decimal;
}

.example:before {
    content: counter(item, decimal) ' ';
    counter-increment: item;
}

@media (max-width: 10px) {
    body {
        counter-reset: item 3;
    }
}

You will see the numbers go from 1 to 5 and when you change the query limit to 1000 it goes to 4 to 8

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
Slava Shpitalny
  • 3,965
  • 2
  • 15
  • 22