Advertisement
Guest User

Editors

a guest
Feb 27th, 2014
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //Object with the content of one page
  2. function Editor(id) {
  3.     this.id = id;
  4.     this.title = 'Page ' + (this.id + 1);
  5.     this.content = '';
  6. }
  7.  
  8. function createEditor() {
  9.     var id = editors.length;
  10.     var ed = new Editor(id)
  11.    
  12.     //Adds menu item
  13.     $('#editorMenu').append('<li data-id="'+ ed.id +'"><a href="#" class="menuLink">'+ ed.title +'</a> <a href="#" class="delete">[X]</a></li>');
  14.     editors.push(ed);
  15.    
  16.     changeEditor(ed);
  17. }
  18.  
  19. //Checks so the object isn't deleted
  20. //and returns the object
  21. function getEditor(id) {
  22.     if(editors[id] != undefined) {
  23.         return editors[id];
  24.     }else {
  25.         return false;
  26.     }
  27. }
  28.  
  29. //Sets title and content from input fields to object
  30. function updateEditor(id) {
  31.     var ed = getEditor(id);
  32.     if(ed !== false) {
  33.         ed.content = $('#editorArea').val();
  34.         ed.title = $('#editorTitle').val();
  35.     }
  36. }
  37.  
  38. //Gets data from object and changes data in the input fields
  39. function changeEditor(ed) {
  40.     $('li').removeClass('active');
  41.     $('li[data-id='+ed.id+']').addClass('active');
  42.     $('#editorTitle').val(ed.title).data('id', ed.id);
  43.     $('#editorArea').val(ed.content).data('id', ed.id);
  44. }
  45.  
  46. //Runs if you change page in the menu
  47. $(document).on('click', '.menuLink', function(e) {
  48.     var id = $(this).parent('li').data('id');
  49.     ed = getEditor(id);
  50.     if(ed !== false) {
  51.         changeEditor(editors[id]);
  52.     }
  53.     e.preventDefault();
  54. });
  55.  
  56. //Runs if you click [X]
  57. $(document).on('click', '.delete', function(e) {
  58.     var id = $(this).parent('li').data('id');
  59.     $('li[data-id='+id+']').remove();
  60.    
  61.     //Leaves undefined in editors at the index with id
  62.     delete(editors[id]);
  63.    
  64.     var items = $('#editorMenu > li');
  65.     if(items.length === 0) {
  66.         createEditor();
  67.     }else {
  68.         changeEditor(editors[$(items[0]).data('id')]);
  69.     }
  70.    
  71.     e.preventDefault();
  72. });
  73.  
  74. //Runs when you click New page
  75. $('#newPage').on('click', function(e) {
  76.     createEditor();
  77.     e.preventDefault();
  78. });
  79.  
  80. //Runs when you type in the title field or the textarea
  81. $('#editorTitle, #editorArea').on('keydown keyup', function(e) {
  82.     var id = $(this).data('id');
  83.     updateEditor(id);
  84. });
  85.  
  86. //All pages
  87. var editors = [];
  88. createEditor();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement