Live Site JS Reference

runOnReady

Run code once a page has been fully loaded. By default, Duda websites use AJAX/Animated navigation to change pages. This means that there is no DOM ready event when a user browses to a new page of the website. Using this lets you know once the user has either loaded the page fully for the first time or browses to a new page of the website.

<script>
dmAPI.runOnReady('nameSpace',callbackFn)
</script>
<script>
//listen to page load or change and run some code
dmAPI.runOnReady('name',function(){
    //execute some code here
});
</script>

Argument

Required

Description

Namespace

No

Pass a unique name that won't collide with other runOnReady function calls

Callback

No

Pass a callback function to execute

loadScript

The best way to load external scripts is through the Duda loadScript function. Using this ensures that the script is loaded asynchronously and the page is ready to handle the script. The script is automatically executed once it's finished. Duda calls the callback function, so any operations you want to take after it is loaded.

<script>
dmAPI.loadScript('https://cdn.jsdelivr.net/npm/[email protected]', function() { 
    // run init code after library loads
    var typed = new Typed('.element', {
        strings: ["First sentence.", "Second sentence."],
        typeSpeed: 30
    });
});
</script>

Argument

Required

Description

url

Yes

A string containing the URL where the JS file lives

Callback

No

Pass a callback function to execute after the script has successfully loaded

runBeforeAjaxNavigation

Run code once right before a page change is started. Duda uses AJAX to handle page changes on published sites. This method allows you to listen for a page change.

<script>
dmAPI.runBeforeAjaxNavigation('nameSpace',callbackFn)
</script>
<script>
//listen to page change 
dmAPI.runBeforeAjaxNavigation('name',function(){
    //execute some code here
});
</script>

Argument

Required

Description

Namespace

No

Pass a unique name that won't collide with other runBeforeAjaxNavigation function calls

Callback

No

Pass a callback function to execute

getSiteName

Get the unique name of the Duda website this code is loading on. This is a unique string that represents a single Duda website. This is usually an 8 or 32 character string.

const siteName = dmAPI.getSiteName();

getSiteExternalId

Get the External reference identifier for this website. This is set when the website was created via the API or updated. It is usually an external identifier passed to Duda for integration purposes.

const externalId = dmAPI.getSiteExternalId();

getSitePlanID

Get the Duda plan id for the current site.

const planId = dmAPI.getSitePlanID();

getCurrentDeviceType

Get the current device type. This function returns desktop, tablet or mobile. The device type detection is done on the server-side via the User-Agent. This always returns the same device type that was detected on the server-side.

const device = dmAPI.getCurrentDeviceType();

getNavItems

Returns an array of objects that contains details about the pages of the website. For each page within the website, the following details will be returned.

Name

Type

Description

title

String

The name of the page, as it appears in the navigation list

alias

String

The internal name of the page. This is unique across the website. It also corelates with the page name in the path

path

String

The relative path to the page

inNavigation

Boolean

If the page is visible to the user. This correlates to the hide page feature in the page settings. Note that this value is respective to the device, so it can be false on desktop and true on mobile

subNav

Array

An array of nested pages following the same structure. A Duda website can have up to two layers of sub nav. (For a total of 3 layers deep)

<script>
// Assign to nav variable
const navLinks = dmAPI.getNavItems();

// loop through each nav item and print to console
nav.forEach(function(e) { 
    console.log(e) 
})

// outputs:
// {title: "HOME", alias: "home", path: "/", inNavigation: false, subNav: Array(0)}
// {title: "SERVICES", alias: "services", path: "/services", inNavigation: true, subNav: Array(3)}
// {title: "TEAM", alias: "team", path: "/team", inNavigation: true, subNav: Array(0)}
// {title: "PRODUCTS", alias: "products", path: "/products", inNavigation: true, subNav: Array(0)}
// {title: "GALLERY", alias: "gallery", path: "/gallery", inNavigation: true, subNav: Array(0)}
// {title: "CONTACT", alias: "contact", path: "/contact", inNavigation: true, subNav: Array(0)}
</script>

getCollection

Get data for a given collection on the website. The collection must already exist and the website must be published with it.

Note, this API is deprecated and we recommend relying on the Collections API.

dmAPI.getCollection({collectionName: 'employees'}).then(
    function(data){ 
    console.log(data); 
  }
)

// returns an array of objects from the employees collection. 
// an empty array is returned if an invalid collection is passed

drawMap

Use Duda's built in map tool to create a map element. This uses Duda's integration with Mapbox to draw a map with a pinned location. When you call the drawMap function, you pass a selector. Duda replaces all the inner contents of that element with the map. You also need to pass the latitude and longitude coordinates or an address string.

<script> 
  
// passing address
dmAPI.drawMap(
  {
    container: '.selector' , 
    addressQuery: '577 College Ave., Palo Alto, CA'
  }
); 

// passing latitude + longitude coordinates
dmAPI.drawMap(
  {
    container: '.selector' , 
    lat: 37.4252935, 
    lng: -122.1504151
  }
);

</script>

getOpimizedImageURL

Returns a URL to a resized image based on user device or an optional width argument. The original image must be stored in Duda. If the image format is not recognized, the method returna the original URL. This can be used in conjunction with a custom widget to display appropriately sized images.

<script>
  // return a 500px wide image
  dmAPI.getOptimizedImageURL('<IMAGE_URL>', 500);

    // return a resized image based on user device
    // Mobile: 640px, Tablet: 1280px, Desktop: 1920px
    dmAPI.getOptimizedImageURL('<IMAGE_URL>');

  // usage within a custom widget
  // data and element variables are
  // provided by the widget builder

  data.config.list.forEach(item => {
    var imgsrc = dmAPI.getResizedImageURL(item.image);
    var elem = document.createElement("img");
    elem.setAttribute("src", imgsrc);
    element.appendChild(elem);
  });
</script>

📘

Using the standard device sizes results in a slight performance boost. Specifying a specific width results in images being resized at request time, while the standard sizes are created and saved when the image is added via the API or editor.

subscribeEvent

Subscribe to specific conversion focused events that happen within the website. This allows you to execute a callback function when a conversion event happens. This API is usually combined with custom analytics or tracking solutions that are placed within Duda websites.

Some events pass data into the callback function for you to take further action on.

<script>
//subscribe to form submit event
dmAPI.subscribeEvent(dmAPI.EVENTS.FORM_SUBMISSION, function(data) {
    console.log("Form data is: " + data);
});
</script>

Argument

Required

Description

Event Name

Yes

Event name (ex. dmAPI.MAP_BUTTON_CLICK)

Callback

No

Pass a callback function to execute

Description of events:

Event

Data provided to Callback

Description

FORM_SUBMISSION

Object with form data in key-value form

When a Duda contact form is submitted on the website

CLICK_TO_CALL

(none)

Click to call button is clicked

EMAIL_BUTTON_CLICK

(none)

Click to email button is clicked

MAP_BUTTON_CLICK

(none)

Click to map button is clicked

SHARE_CLICK

(none)

Click to share button is clicked

OPENTABLE_CLICK

(none)

Click to reserve button is clicked

NOTIFICATION_LINK_CLICK

(none)

When a link within the notification bar is clicked

NOTIFICATION_LINK_CLOSE

(none)

When a notification bar is closed (ex. the "x" is clicked)

COUPON_CLICK

(none)

When a coupon is clicked or viewed on the website

STORE_ORDER

(none)

Once a successful purchase happens within an eCommerce store

SHOW_POPUP

(none)

When a pop-up is displayed on a website. Either from a personalization rule or button click

PERSONALIZATION_RULE_IMPRESSION

Personalization rule: {ruleId, ruleType}

When a personalization rule is successfully loaded on a page

PERSONALIZATION_RULE_LINK_CLICK

(none)

Only runs for links clicked within the 'new row' personalization rule

subscribeToAllEvents

Subscribe to all the possible site events that can happen. Note that not all events are 'conversion' events, so make sure you only track the events you specifically want to. You can see all the available events above.

<script>
//subscribe to all events
dmAPI.subscribeToAllEvents(function(eventName, data) {
    console.log('Event: ' + eventName  + ' was called');
});
</script>

loadCollectionsAPI

Load the collections API to query the data in your collections programmatically. This API has filtering, pagination, and sorting options.

<script>
//load the collections API
dmAPI.loadCollectionsAPI().then(api => {
    api.data("my-collection")
        .where("field-name", "eq", "some-value")
        .orderBy("other-field-name")
        .pageSize(10)
        .get()
        .then(json => console.log(json))
})
</script>

Did this page help you?