Skip to Content

pre()

Function for handling selecting and copying text within Nebula pre tags.

JavaScript July 2, 2019

Usage

JavaScript
nebula.pre()

Parameters

This function does not accept any parameters. Is this incorrect?

Additional Notes

This function is called automatically if Nebula pre tags are used.

Source File

Located in /assets/js/nebula.js on line 4285.

JavaScript
nebula.pre = function(){
    //Format non-shortcode pre tags to be styled properly
    jQuery('pre.nebula-code').each(function(){
        if ( !jQuery(this).parent('.nebula-code-con').length ){
            var lang = jQuery(this).attr('class').replace('nebula-code', '').trim();
            jQuery(this).addClass(lang.toLowerCase()).wrap('<div class="nebula-code-con clearfix ' + lang.toLowerCase() + '"></div>');
            jQuery(this).closest('.nebula-code-con').prepend('<span class="nebula-code codetitle ' + lang.toLowerCase() + '">' + lang + '</span>');
        }
    });

    //Manage copying snippets to clipboard
    if ( 'clipboard' in navigator ){
        jQuery('.nebula-code-con').each(function(){
            jQuery(this).append('<a href="#" class="nebula-selectcopy-code">Copy to Clipboard</a>');
            jQuery(this).find('p:empty').remove(); //Sometimes WordPress adds extra/empty <p> tags. These mess with spacing, so we remove them.
        });

        nebula.dom.document.on('click', '.nebula-selectcopy-code', function(){
            var oThis = jQuery(this);
            if ( oThis.hasClass('error') ){ //If we already errored, stop trying
                return false;
            }

            var text = jQuery(this).closest('.nebula-code-con').find('pre').text();

            navigator.clipboard.writeText(text).then(function(){
                oThis.text('Copied!').removeClass('error').addClass('success');
                setTimeout(function(){
                    oThis.text('Copy to clipboard').removeClass('success');
                }, 1500);
            }).catch(function(e){ //This can happen if the user denies clipboard permissions
                ga('send', 'exception', {'exDescription': '(JS) Clipboard API error: ' + e.data, 'exFatal': false});
                oThis.text('Unable to copy.').addClass('error');
            });

            return false;
        });
    }
};

Override

To override or disable this JavaScript function, simply redeclare it with the exact same function name.

JavaScript
nebula.pre = function(){
    //Write your own code here, leave it blank, or return false.
}