tags:

views:

19

answers:

1

Hello,

I'm trying to write a bit in Javascript for a mobile website. I've searched all over Google and found some help, but I'm having some kind of problem implementing it.

In the HTML Header (note, no CSS file specified here):

<script type="text/javascript" src="scrnsz.js"></script>

JavaScript:

if (screen.width > 200) {
link = document.getElementsByTagName("link")[0];
link.href = "style.css";
}

if (screen.width <= 200) {
link = document.getElementsByTagName("link")[0];
link.href = "smstyle.css";
}

Can any pros help? :) Thank you.

A: 

To make that work, you'd need a lone <link rel='stylesheet'> instruction in your HEAD. The script will search for the first one it finds, and replace the href accordingly.

However, there are more ways and options to prepare a site for mobile browsers. Check out these SO questions:

there are many more discussions on SO dealing with this - check them out using the search.

Pekka
That alone didn't work for me, it just still didn't include the CSS. I also tried pointing it (href) to one of the stylesheets to see if it correctly switched to the other, but no luck.
Anders H
I should have included more originally. The entire website is mobile, but it needs a simpler stylesheet for mobile phone under 200px wide. As far as I can tell, changing the CSS include to @media handheld would just create the same issue.
Anders H
It should work if you put the link element before the Javascript include. However, it would be best to put in the `onload` event of the page to ensure the DOM is fully available. Are you using a Javascript framework like JQuery or Prototype?
Pekka
No, just pure JS. I moved the <link rel> element above the JS and that worked for me. I may run into issues if I don't use onload though?
Anders H
You shouldn't run into issues in this ase because the link element *should* always exist when the script is called, but I wouldn't rely on it. You can do it using window.onload() no problem. If you want to use a framework, here is a starting point for JQuery: http://15daysofjquery.com/quicker/4/ there are other frameworks around, but that is a different discussion.
Pekka