javascript - Set Viewport Meta Parameters Based on the Width of Browser Window -
i want set different parameters viewport meta tag, depending on current browser window, , able change them on resize (removing current viewport meta tag(s) first , replacing new one. have script think should that, reason script nothing. i'm missing something, can't quite figure out what.
here's script:
<script type="text/javascript"> var width = window.clientwidth; var meta = document.createelement("meta"); var head = document.getelementsbytagname("head")[0]; if (width < 960) { meta.setattribute("name", "viewport"); meta.setattribute("content", "width=device-width, initial-scale=0.5"); head.appendchild(meta); } else { meta.setattribute("name", "viewport"); meta.setattribute("content", "width=device-width, initial-scale=1"); head.appendchild(meta); }; window.onresize = function(event) { width = window.clientwidth; var metas = document.getelementsbytagname("meta"); (var = 0; < metas.length; i++) { if (metas[i].getattribute("name") == "viewport") { head.removechild(metas[i]); } } if (width < 960) { meta.setattribute("name", "viewport"); meta.setattribute("content", "width=device-width, initial-scale=0.78"); head.appendchild(meta); } else { meta.setattribute("name", "viewport"); meta.setattribute("content", "width=device-width, initial-scale=1"); head.appendchild(meta); } }; </script>
how make work?
1. window.clientwidth
may not work in browsers. safer way viewport width using plain javascript is:
var width = window.innerwidth || document.documentelement.clientwidth || document.body.clientwidth;
2. there's typo in for
loop. change comma semi-colon. typo causing code in script
tag crash.
for (var = 0; < metas.length; i++) { ... }
3. current width wasn't getting retrieved in onresize event handler. still using initial viewport width.
window.onresize = function(event) { width = window.innerwidth || document.documentelement.clientwidth || document.body.clientwidth; ... }
Comments
Post a Comment