Skip to Content
Menu

uniqueId()

Generate a CSS-safe unique ID that always begins with a letter.

JavaScript January 23, 2023

Usage

JavaScript
nebula.uniqueId(prefix, random)

Parameters

prefix
(Optional) (String) Prepend a specific prefix string to the ID
Default: nuid

random
(Optional) (Boolean) Append a random number to the end of the ID
Default: false

Parameter Notes

Remember that if you override the prefix that starts with a number that may not be valid for use in CSS selectors!

Request or provide clarification »

Examples

Create a div with a unique ID

JavaScript
jQuery('<div id="' + nebula.uniqueId() + '"></div>'); //Create a div in JavaScript with a unique ID
Was this page helpful? Yes No


    A feedback message is required to submit this form.


    Please check that you have entered a valid email address.

    Enter your email address if you would like a response.

    Thank you for your feedback!

    Source File

    Located in /assets/js/modules/utilities.js on line 389.

    No Hooks

    This function does not have any filters or actions available. Request one?
    JavaScript
    nebula.uniqueId = function(prefix='nuid', random=false){
        const seconds = Date.now() * 1000 + Math.random() * 1000; //Convert the current time into seconds
        const id = seconds.toString(16).replace(/\./g, '').padEnd(14, '0'); //Convert the timestamp into a base 16 string, remove decimal symbol, and set a minimum length (and always begin with a letter)
    
        if ( random ){
            return prefix + id + '.' + Math.trunc(Math.random()*100000000); //Append a random number to the end if randomness is requested
        }
    
        return prefix + id;
    };
    

    Override

    To override or disable this JavaScript function, simply redeclare it with the exact same function name. Remember: Some functionality is conditionally loaded via dynamic imports, so if your function is not overriding properly, try listening for a DOM event (described below).

    JavaScript

    For non-module import functions:

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


    For dynamically imported module function overrides:

    jQuery(window).on('load', function(){
        nebula.uniqueId = function(prefix, random){
            //Write your own code here, leave it blank, or return false.
        }
    });


    Custom Nebula DOM events do also exist, so you could also try the following if the Window Load listener does not work:

    jQuery(document).on('nebula_module_loaded', function(module){
        //Note that the module variable is also available to know which module specifically was imported
        if ( typeof nebula.uniqueId === 'function' ){
            nebula.uniqueId = function(prefix, random){
                //Write your own code here, leave it blank, or return false.
            }
    	}
    });