I want to calculate the screen width and assign that result to a number between, say, 0 and 3, for example. I am trying to use iron-media-query to do this.
I expect to see (logged to the console) one of the queries return a value of true and the other three to return false. However, they all return a value of undefined.
What am I doing wrong?
FYI, After I solve this, I plan to add a conditional to the queryResult() method to store the value of index when queryMatches is true.
queryResult: function() {
...
if(this.queryMatches) {
this.set('mediaWidth', index);
}
...
}
http://jsbin.com/kamusivebi/1/edit?html,console,output
<!doctype html>
<head>
<meta charset="utf-8">
<base href="https://polygit.org/components/">
<script src="webcomponentsjs/webcomponents-lite.min.js"></script>
<link href="polymer/polymer.html" rel="import">
</head>
<body>
<dom-module id="x-element">
<template>
<style></style>
<template is="dom-repeat"
id="page"
items="[[queries]]"
>
<iron-media-query id="query"
full
query="[[item]]"
query-matches="{{queryMatches}}"
>
<span hidden>{{queryResult(index)}}</span>
</iron-media-query>
</template>
</template>
<script>
(function(){
Polymer({
is: "x-element",
properties: {
queryMatches: Boolean,
queries: {
type: Object,
value: function() {
return [
'(max-width: 699px)' ,
'(min-width: 700px) AND (max-width: 899px)' ,
'(min-width: 900px) AND (max-width: 1124px)' ,
'(min-width: 1125px)' ,
];
},
},
},
queryResult: function(index) {
this.set('mediaWidth', index);
console.log('mediaWidth', this.mediaWidth);
console.log('queryMatches', this.queryMatches);
},
});
})();
</script>
</dom-module>
<x-element></x-element>
</body>
Two problems:
You're incorrectly binding the results of each
iron-media-queryto a singlequeryMatchesproperty, so each iteration would overwrite the results of the previous iteration. To correct this, you could bind to a sub-property of theitemiterator (e.g.,item.queryMatches), which requires changing the type ofqueriesfrom aStringarray into anObjectarray. Then, you could passitem.queryMatchestoqueryResult().Your demo is missing the HTML import for
<iron-media-query>, soqueryMatcheswould always beundefined.Here's a demo with the corrections:
codepen