Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Auto Save | Delay #856

Closed
tauseefk opened this issue Oct 28, 2015 · 5 comments
Closed

Auto Save | Delay #856

tauseefk opened this issue Oct 28, 2015 · 5 comments
Labels

Comments

@tauseefk
Copy link

Hey I'm trying to create a kind of auto save for the editor. I want to trigger it 1 second after the user stops typing. So I tried attaching the delay helper function.

var triggerAutoSave = function(event, editable){
 console.log("hey");
}

// Listening to editable events starts here
editor.subscribe('editableInput', editor.delay(triggerAutoSave));

Can you help me figure out a way to use the delay for that purpose and also reset the timeout every time a key is pressed.

@nmielnik
Copy link
Member

I think what you want to use instead is MediumEditor.util.throttle(func, wait) where func is the method you want to delay, and wait is the amount of milliseconds to delay. It's essentially just a copy & paste of underscore's debounce()

So you would do something like this:

var triggerAutoSave = function (event, editable) {
    console.log('hey');
};

var throttledAutoSave = MediumEditor.util.throttle(triggerAutoSave, 1000); // 1 second

// Listening to editable events starts here
editor.subscribe('editableInput', throttledAutoSave);

You can find the code here.

@tauseefk
Copy link
Author

Hey that does the job quite well, thanks 💃

@nmielnik
Copy link
Member

👍

@AmirMustafa
Copy link

Hello,
I am facing the same issue in auto save functionality in medium editor.
Please advice me how to implement it properly.

This is my code:

<script src="medium/plugins/medium-editor-mobile-plugin-master/dist/medium-editor-mobile-plugin.js"></script> <script src="medium/plugins/handlebars/handlebars.runtime.min.js"></script> <script src="medium/plugins/jquery-sortable/source/js/jquery-sortable-min.js"></script> <script src="medium/plugins/blueimp-file-upload/js/vendor/jquery.ui.widget.js"></script> <script src="medium/plugins/blueimp-file-upload/js/jquery.iframe-transport.js"></script> <script src="medium/plugins/blueimp-file-upload/js/jquery.fileupload.js"></script> <script src="medium/plugins/medium-editor-insert-plugin/dist/js/medium-editor-insert-plugin.js"></script> <script src="medium/plugins/jquery-cycle2/build/jquery.cycle2.min.js"></script> <script src="medium/plugins/jquery-cycle2/build/plugin/jquery.cycle2.center.min.js"></script> <script src="medium/plugins/spectrum/spectrum.js"></script> <script type = "text/javascript" src="medium/js/medium-editor-color-picker.js"></script> <script type = "text/javascript" src="medium/plugins/medium-editor-embed-button/dist/js/medium-editor-embed-button.js"></script> <script type = "text/javascript" src="medium/js/custom-html.js"></script>

<textarea class="editable txt-style" name="medium_editor" id="" cols="80%" rows="100%" onKeyUp='characterCount(this)'>
                </textarea>
            </div>
        </div>
        <div class="row">
            <div class="col-md-offset-2 col-md-8 col-xs-12 mt-20">
                <button type="submit" class="btn btn-primary pull-right ">Publish</button>
            </div>
        </div>
    </form>

/* ==================== Main Editor Script: Start ==================== */

    var editor = new MediumEditor('.editable', {
  /* These are the default options for the editor,
      if nothing is passed this is what is used */
  activeButtonClass: 'medium-editor-button-active',
  allowMultiParagraphSelection: true,
  buttonLabels: true,
  toolbar: {
  buttons: [
        //'undo',
       // 'redo',
       'fontsize',
       'colorPicker',
        'bold',
        'italic',
        'underline',
        'embedButton',
        'anchor', 
        //'orderedlist',  
        //'quote',
       // 'table',
       //'fontname',
        'unorderedlist',
        'justifyLeft',
        'justifyCenter',
        'justifyRight',
        'justifyFull',
        'indent',
        'outdent'
        //'print',
        //'download',
       // 'toolbar_states',
       /* {
            name: 'image',
            action: 'append-img',
            aria: '',
            tagNames: ['img'],
            contentDefault: '<b>Justify</b>',
            classList: ['custom-class-h1'],
            attrs: {
                'data-custom-attr': 'attr-value-h1'
            }
        },*/
        
    ],
        sticky:true,
        align:'center',
        static:true
  },
  contentWindow: window,
  delay: 0,
  disableReturn: false,
  disableDoubleReturn: false,
  disableExtraSpaces: true,
  disableEditing: false,
  disableImageResize: false,
  imageMaxWidth: 24000,

imageMaxHeight: 24000,
elementsContainer: false,
extensions: {},
ownerDocument: document,
spellcheck: true,
targetBlank: false,

  paste: {
      forcePlainText: false,
      cleanPastedHTML: true,
      cleanReplacements: [],
      cleanAttrs: ['class', 'style', 'dir'],
      cleanTags: ['meta']
    },
extensions: {               //Custom Extentions
  table: new MediumEditorTable(),
  embedButton: new EmbedButtonExtension({
                embedOpts: {    //Added extention Embed
                    oembedProxy: "https://iframe.ly/api/oembed?api_key=3bef8c4238179ff9306315&url="
                }     /*Added medium editor's library on line 17 and 41*/
            }),
  'colorPicker': pickerExtension,
   "customHtml": new CustomHtml({
            buttonText: "Divider"
          , htmlToInsert: "<hr class='someclass'>"
        })

},
placeholder:
        {
            text:'Create your campaign here', 
            hideOnClick:true
        }

});

/* ==================== Main Editor Script: End ==================== */

@AmirMustafa
Copy link

AmirMustafa commented Feb 27, 2017

<?php include("profile-header-2.php");
?> <!DOCTYPE html> <html> <head> <!--==============Medium Editor CSS FILES: START==============--> <link rel="stylesheet" href="medium/css/medium-editor.css"> <link rel="stylesheet" href="medium/css/themes/mani.css"> <link rel="stylesheet" href="medium/css/medium-editor-tables.css"> <link href="http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet"> <link rel="stylesheet" href="medium/plugins/medium-editor-insert-plugin/dist/css/medium-editor-insert-plugin.css"> <link rel="stylesheet" href="medium/plugins/medium-editor-insert-plugin/dist/css/medium-editor-insert-plugin-frontend.min.css"> <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.css"> <link rel="stylesheet" href="medium/plugins/spectrum/spectrum.css"> <link rel="stylesheet" href="medium/plugins/medium-editor-embed-button/dist/css/medium-editor-embed-button.css"> <!--==============Medium Editor CSS FILES: END==============--> <!--==============Medium Editor JS FILES: START==============--> <script src="medium/plugins/jquery/dist/jquery.min.js"></script> <script src="medium/js/medium-editor.js"></script> <script src="medium/js/util.js"></script> <script type="text/javascript" src="medium/js/medium-editor-tables.js"></script> <script src="medium/plugins/medium-editor-mobile-plugin-master/dist/medium-editor-mobile-plugin.js"></script> <script src="medium/plugins/handlebars/handlebars.runtime.min.js"></script> <script src="medium/plugins/jquery-sortable/source/js/jquery-sortable-min.js"></script> <script src="medium/plugins/blueimp-file-upload/js/vendor/jquery.ui.widget.js"></script> <script src="medium/plugins/blueimp-file-upload/js/jquery.iframe-transport.js"></script> <script src="medium/plugins/blueimp-file-upload/js/jquery.fileupload.js"></script> <script src="medium/plugins/medium-editor-insert-plugin/dist/js/medium-editor-insert-plugin.js"></script> <script src="medium/plugins/jquery-cycle2/build/jquery.cycle2.min.js"></script> <script src="medium/plugins/jquery-cycle2/build/plugin/jquery.cycle2.center.min.js"></script> <script src="medium/plugins/spectrum/spectrum.js"></script> <script type="text/javascript" src="medium/js/medium-editor-color-picker.js"></script> <!-- <script type="text/javascript" src="medium/js/fontname.js"></script>--> <script type="text/javascript" src="medium/plugins/medium-editor-embed-button/dist/js/medium-editor-embed-button.js"></script> <script type="text/javascript" src="medium/js/custom-html.js"></script> <!--==============Medium Editor JS FILES: END==============--> </head> <body> <div class="container"> <div class="row"> <form action="campaign-dbm.php" method="post"> <div class="row"> <div class="col-lg-offset-2 col-lg-8 col-md-offset-2 col-md-8 col-sm-offset-2 col-sm-8 col-xs-offset-1 col-xs-10 "> <br> <textarea class="editable txt-style" name="medium_editor" id="" cols="80%" rows="100%" onKeyUp='characterCount(this)'> </textarea> </div> </div> <div class="row"> <div class="col-md-offset-2 col-md-8 col-xs-12 mt-20"> <button type="submit" class="btn btn-primary pull-right ">Publish</button> </div> </div> </form> </div> </div> <!-- <div class="editable" style="width: 80%; height:80%;"></div> --> <!-- <form action="campaign-dbm.php" method="post"> <br><br><br><br><br><br> --> <!-- <textarea style="height:750px; overflow-y:auto; box-shadow:0px 0px 5px #595959; margin-left:15%; margin-right:15%; padding-left: 5%; padding-right: 5%; padding-top: 2.5%; padding-bottom: 2.5%;" class="editable" name="medium_editor" id="" cols="80%" rows="100%"></textarea> <button type="submit" class="btn btn-primary pull pull-right" style="margin-right:18%; margin-top:2%;">Publish</button> --> <!-- <script>var editor=new MediumEditor('.editable');
</script> --> <!-- <script> var editor=new MediumEditor('.editable', {
    /* These are the default options for the editor,
          if nothing is passed this is what is used */
    activeButtonClass: 'medium-editor-button-active', allowMultiParagraphSelection: true, buttonLabels: true, contentWindow: window, delay: 0, disableReturn: false, disableDoubleReturn: false, disableExtraSpaces: false, disableEditing: false, elementsContainer: false, extensions: {}
    , ownerDocument: document, spellcheck: true, targetBlank: false
}

);
</script> --> <script>
/* ==================== Main Editor Script: Start ==================== */

var editor=new MediumEditor('.editable', {
    /* These are the default options for the editor,
          if nothing is passed this is what is used */
    activeButtonClass: 'medium-editor-button-active', allowMultiParagraphSelection: true, buttonLabels: true, toolbar: {
        buttons: [ //'undo',
        // 'redo',
        'fontsize', 'colorPicker', 'bold', 'italic', 'underline', 'embedButton', 'anchor', //'orderedlist',  
        //'quote',
        // 'table',
        //'fontname',
        'unorderedlist', 'justifyLeft', 'justifyCenter', 'justifyRight', 'justifyFull', 'indent', 'outdent' //'print',
        //'download',
        // 'toolbar_states',
        /* {
                name: 'image',
                action: 'append-img',
                aria: '',
                tagNames: ['img'],
                contentDefault: '<b>Justify</b>',
                classList: ['custom-class-h1'],
                attrs: {
                    'data-custom-attr': 'attr-value-h1'
                }
            },*/
        ], sticky: true, align: 'center', static: true
    }
    , contentWindow: window, delay: 0, disableReturn: false, disableDoubleReturn: false, disableExtraSpaces: true, disableEditing: false, disableImageResize: false, imageMaxWidth: 24000, imageMaxHeight: 24000, elementsContainer: false, extensions: {}
    , ownerDocument: document, spellcheck: true, targetBlank: false, paste: {
        forcePlainText: false, cleanPastedHTML: true, cleanReplacements: [], cleanAttrs: ['class', 'style', 'dir'], cleanTags: ['meta']
    }
    , extensions: {
        //Custom Extentions
        table: new MediumEditorTable(), embedButton: new EmbedButtonExtension( {
            embedOpts: {
                //Added extention Embed
                oembedProxy: "https://iframe.ly/api/oembed?api_key=3bef8c4238179ff9306315&url="
            }
            /*Added medium editor's library on line 17 and 41*/
        }
        ), 'colorPicker': pickerExtension, "customHtml": new CustomHtml( {
            buttonText: "Divider", htmlToInsert: "<hr class='someclass'>"
        }
        )
    }
    , placeholder: {
        text: 'Create your campaign here', hideOnClick: true
    }
}

);

/* ==================== Main Editor Script: End ==================== */


/* ========= JavaScritpt for showing value in editor's slider: Start ========= */

document.querySelector('input[type=range]').addEventListener('input', function rangeChange() {
    // trigger the CSS to update
    this.setAttribute('value', this.value);
}

);

/* ========= JavaScritpt for showing value in editor's slider: Start ========= */


/* ====================== For Image Grid Play functionality: Start ====================== */

$(function () {
    $('.editable').mediumInsert( {
        editor: editor, addons: {
            images: {
                uploadScript: null, deleteScript: null, captionPlaceholder: 'Type caption for image', styles: {
                    slideshow: {
                        label: '<span class="fa fa-play"></span>', added: function ($el) {
                            $el .data('cycle-center-vert', true) .cycle( {
                                slides: 'figure'
                            }
                            );
                        }
                        , removed: function ($el) {
                            $el.cycle('destroy');
                        }
                    }
                }
                , actions: null
            }
        }
    }
    );
}

);
(function(i, s, o, g, r, a, m) {
    i['GoogleAnalyticsObject']=r;
    i[r]=i[r]||function() {
        (i[r].q=i[r].q||[]).push(arguments)
    }
    , i[r].l=1*new Date();
    a=s.createElement(o), m=s.getElementsByTagName(o)[0];
    a.async=1;
    a.src=g;
    m.parentNode.insertBefore(a, m)
}

)(window, document, 'script', '../../www.google-analytics.com/analytics.js', 'ga');
ga('create', 'UA-44692164-1', 'auto');
ga('send', 'pageview');
</script> <!--==================Slider Indicator: Start==================--> <script> var el,
newPoint,
newPlace,
offset;
// Select all range inputs, watch for change
$("input[type='range']").change(function() {
    // Cache this for efficiency
    el=$(this);
    // Measure width of range input
    width=el.width();
    // Figure out placement percentage between left and right of input
    newPoint=(el.val() - el.attr("min")) / (el.attr("max") - el.attr("min"));
    offset=-1;
    // Prevent bubble from going beyond left or right (unsupported browsers)
    if (newPoint < 0) {
        newPlace=0;
    }
    else if (newPoint > 1) {
        newPlace=width;
    }
    else {
        newPlace=width * newPoint + offset;
        offset -=newPoint;
    }
    // Move bubble
    el .next("output") .css( {
        left: newPlace, marginLeft: offset + "%"
    }
    ) .text(el.val());
}

) // Fake a change to position bubble at page load
.trigger('change');
</script> <!-- ASCII CODE SCRIPT: START --> <script type="text/javascript"> var maxLength=160;
var Ascii=true;
function isAscii(el) {
    var i=0;
    while ( i <=el.value.length) {
        if(el.value[i].charCodeAt(0) >=0 && el.value[i]charCodeAt(0) <=127) {
            i=i+1;
        }
        else {
            return false
        }
    }
    return true;
}

function characterCount(el) {
    if ( isAscii(el)) {
        Ascii=true;
        maxLength=160;
    }
    else {
        Ascii=false maxLength=70;
    }
    var charCount=document.getElementById('charCount');
    if (el.value.length > maxLength) el.value=el.value.substring(0, maxLength);
    if (charCount) charCount.innerHTML=maxLength - el.value.length;
    return true;
}

</script> <!-- ASCII CODE SCRIPT: END --> <!--==================Slider Indicator: End==================--> <!-- <script> var editor=new MediumEditor('.editable', {
    toolbar: {
        /* These are the default options for the toolbar,
             if nothing is passed this is what is used */
        allowMultiParagraphSelection: true, buttons: ['bold', 'italic', 'underline', 'anchor', 'h2', 'h3', 'quote'], diffLeft: 0, diffTop: -10, firstButtonClass: 'medium-editor-button-first', lastButtonClass: 'medium-editor-button-last', relativeContainer: null, standardizeSelectionStart: false, static: false, /* options which only apply when static is true */
        align: 'right', sticky: false, updateOnEmptySelection: false, placeholder: {
            /* This example includes the default options for placeholder,
             if nothing is passed this is what it used */
            text: 'Type your text', hideOnClick: true
        }
    }
}

);
</script> --> <script type="text/javascript"> // setting's nav-button on capaign page js
jQuery(document).ready(function ($) {
    //THIS MAKES THE SLIDEY THINGS SLIDE
    //textone
    if (window.matchMedia("(max-width: 1600px)").matches) {
        jQuery(window).scroll(function () {
            if (jQuery(this).scrollTop() > 75) {
                $(".medium-editor-toolbar").css('top', '0px'); //class where you want apply
            }
            else {
                $(".medium-editor-toolbar").css('top', '69px'); //class where you want apply
            }
        }
        );
    }
}

);
</script> </body> </html>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants