Viewport Size, Screen Resolution, Mouse Postition


/ Published in: JavaScript
Save to your folder(s)

This code is cross-browser compatible and checks the dimensions of the viewport, the screen resolution and the mouseposition which can be quite helpful to perform some checks with JavaScript.


Copy this code and paste it in your HTML
  1. <script type="text/javascript">
  2. function getViewportWidth()
  3. {
  4. if (window.innerWidth)
  5. {
  6. return window.innerWidth;
  7. }
  8. else if (document.body && document.body.offsetWidth)
  9. {
  10. return document.body.offsetWidth;
  11. }
  12. else
  13. {
  14. return 0;
  15. }
  16. }
  17.  
  18. function getViewportHeight()
  19. {
  20. if (window.innerHeight)
  21. {
  22. return window.innerHeight;
  23. }
  24. else if (document.body && document.body.offsetHeight)
  25. {
  26. return document.body.offsetHeight;
  27. }
  28. else
  29. {
  30. return 0;
  31. }
  32. }
  33.  
  34. var tellMeTheSizes=function()
  35. {
  36. document.getElementById("viewportwidth").innerHTML = getViewportWidth() + "px";
  37. document.getElementById("viewportheight").innerHTML = getViewportHeight() + "px";
  38. document.getElementById("resolutionheight").innerHTML = screen.height + "px";
  39. document.getElementById("resolutionwidth").innerHTML = screen.width + "px";
  40. }
  41.  
  42. window.onload=function()
  43. {
  44. tellMeTheSizes();
  45. }
  46.  
  47. window.onresize=function()
  48. {
  49. tellMeTheSizes();
  50. }
  51.  
  52. window.onmousemove=function(event)
  53. {
  54. ev = event || window.event;
  55. document.getElementById("mousetop").innerHTML = ev.pageY + "px";
  56. document.getElementById("mouseleft").innerHTML = ev.pageX + "px";
  57. }
  58. </script>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.