Guest User

Basic widget system, with position retention

a guest
Jul 25th, 2015
38
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.31 KB | None | 0 0
  1. <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
  2. <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
  3.  
  4. <script type="text/javascript">
  5. $( document ).ready(function() {
  6. //Loop through all widget class elements
  7. $('.widget').each(function() {
  8. //Get localstorage values on location
  9. var widgetPosX = localStorage.getItem(this.id+'_posX');
  10. var widgetPosY = localStorage.getItem(this.id+'_posY');
  11.  
  12. //If values are not null, change the element position
  13. if (widgetPosX != null && widgetPosY != null) {
  14. $(this).css('left', widgetPosX);
  15. $(this).css('top', widgetPosY);
  16. }
  17. });
  18. });
  19.  
  20. $(function() {
  21. //Widget dragging
  22. $( ".widget" ).draggable({
  23. grid: [10, 10],
  24. stop: function(event, ui){
  25. //On drag release, get position and save to localstorage
  26. var pos = $(this).position();
  27.  
  28. localStorage.setItem(this.id+'_posX', pos.left);
  29. localStorage.setItem(this.id+'_posY', pos.top);
  30. }
  31. });
  32. });
  33. </script>
  34.  
  35. <style>
  36. HTML, body {
  37. margin: 0px;
  38. padding: 0px;
  39. }
  40. .widget {
  41. position: absolute;
  42. display type: inline-block;
  43. width: 100px;
  44. height: 100px;
  45. background: #ddd;
  46. opacity: .5;
  47. }
  48. </style>
  49.  
  50. <div class="widget" id="widget1">Widget 1</div>
  51. <div class="widget" id="widget2" style="top: 110px;">Widget 2</div>
Advertisement
Add Comment
Please, Sign In to add comment