Hi I've just begun to make my website mobile friendly, but I've hit a roadblock. My Javascript code here is not working in mobile but it's perfect for desktops. In device view in chrome it works perfectly but in mobiles the "document.getElementById("side").style = 'top:' + topheight + 'px;';"doesn't work. I've alerted the values of width and topheight, they returned their values perfectly. I just want to position an "z-index:1" element so that it doesn't overlap the top elements. I've checked this code on 2 phones of 360px and 320px width. Image of the way I want it(Google Developer Tools Device Mode) Image of The Painful Truth(Mobile 640x360px) NOTE: I'VE OMITTED SOME LINES OF CODE WHICH ARE IRRELEVANT TO ENHANCE READABILITY OF THE CODE, 'CAUSE I'M TALKING ABOUT >50 LINES OF CODE HERE ------------------------------------------HERE IS THE CODE------------------------------------ JAVASCRIPT var width = screen.width; alert(width); if(width < 320){ window.location.href = "/root/nomobile.php";} var topheight = document.getElementById('top').offsetHeight; if (document.getElementById("ul") != undefined) { width = document.getElementById("ul").offsetWidth;} if (screen.width > 319) { document.getElementById("side").style = 'top:' + topheight + 'px;';} /* Some other code which are irrelevant to the question*/ HTML <div id="top"> /*Welcome Message If logged in*/ /*Nav Menu*/ </div> <div id="side" class="w3-sidenav"> /*Content*/ </div>
Why are you using javascript to do css's job? I haven't looked closely, but your description of the issue tells me the css solution is simplicity itself. Rule of thumb? Never use javascript for basic functionality. It's an enhancement, not core. cheers, gary
As I mentioned earlier this code is used for responsive design. The value of 'topheight' will change according to device resolution. Since CSS have no method of getting the screen width, I am stuck with js.
Do a Google search again. For example: https://davidwalsh.name/device-state-detection-css-media-queries-javascript or follow gary's signature to learn more about it. CSS rendering engine consumes less power than JavaScript engine on mobile devices, do you know? So help save the earth.
No, you're not. Your current design / layout might be, but that just means your layout/design sucks. There is normally no reason _at all_ to do positioning with JS for regular page-elements with predefined proportions. Even fluid layouts with dynamic proportions can in 99% of cases be done using pure CSS. While JS can be good for swapping out classes and such on the fly, or calculating specific values on movable elements, I see no reason why what you have explained should warrant using JS. You should probably rethink your code, or give us a link to the site in question so we can see what might be done with it.