Skip to main content

API Reference

The Participaite Translate Plugin provides a public API that allows you to programmatically control translations on your website. Please remember to hide the language-selection dropdown by setting the disableLanguageButton: true option in your Config.

Global Object

The plugin exposes its functionality through the global ptpTranslate object.

Methods

translateTo(languageCode)

Triggers the translation of the page to the specified language.

Parameters:

  • languageCode (string): The target language code (e.g., "en", "fr", "es")

Returns: Promise<void>

Example:

// Translate the page to English
ptpTranslate.translateTo("en");

// Example with async/await
async function switchLanguage() {
try {
await ptpTranslate.translateTo("fr");
console.log("Translation to French completed");
} catch (error) {
console.error("Translation failed:", error);
}
}

// Example usage in event handlers
document.getElementById("language-button").addEventListener("click", () => {
ptpTranslate.translateTo("es");
});

Use Cases

Custom Language Switcher

You can create your own language switching UI:

const customLanguageSwitcher = {
init() {
const buttons = document.querySelectorAll(".custom-lang-button");
buttons.forEach((button) => {
button.addEventListener("click", (e) => {
const lang = e.target.dataset.lang;
ptpTranslate.translateTo(lang);
});
});
},
};
<div class="custom-switcher">
<button class="custom-lang-button" data-lang="en">English</button>
<button class="custom-lang-button" data-lang="fr">Français</button>
<button class="custom-lang-button" data-lang="es">Español</button>
</div>

Automated Language Switching

You can automatically switch languages based on user preferences or other conditions:

// Switch based on user's browser language
const userLanguage = navigator.language.split("-")[0];
if (userLanguage !== "de") {
// if not already in German
ptpTranslate.translateTo(userLanguage);
}

// Switch based on URL parameters
const params = new URLSearchParams(window.location.search);
if (params.has("lang")) {
ptpTranslate.translateTo(params.get("lang"));
}

Best Practices

  1. Error Handling: Always implement error handling when using the API programmatically.
  2. Language Validation: Verify that the target language is supported in your configuration before calling translateTo().

Notes

  • The translation process is asynchronous and returns a Promise.
  • The target language must be configured in your PTP_TRANSLATE_CONFIG settings.
  • If an invalid language code is provided, the promise will reject with an error.