{"id":21805,"date":"2025-09-17T17:00:00","date_gmt":"2025-09-17T11:30:00","guid":{"rendered":"https:\/\/meetanshi.com\/blog\/?p=21805"},"modified":"2025-09-20T16:18:12","modified_gmt":"2025-09-20T10:48:12","slug":"useful-hyva-javascript-helper-functions","status":"publish","type":"post","link":"https:\/\/meetanshi.com\/blog\/useful-hyva-javascript-helper-functions\/","title":{"rendered":"Useful Hyv\u00e4 JavaScript Helper Functions for Hyv\u00e4 Developers"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">In this blog post, we have listed the most useful Hyv\u00e4 JavaScript helper functions, which are accessible via the global <code>window.hyva<\/code> object on every storefront page. These functions simplify coding and reduce the chances of frontend errors.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Quick Look<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>Helper Function Name<\/th><th>Main Use<\/th><\/tr><tr><td><code>hyva.getFormKey()<\/code><\/td><td>Retrieves the current Magento form key for secure form submissions.<\/td><\/tr><tr><td><code>hyva.getCookie()<\/code><\/td><td>Safely retrieves the value of a specific cookie.<\/td><\/tr><tr><td><code>hyva.setCookie()<\/code><\/td><td>Sets a cookie with specified name, value, and options.<\/td><\/tr><tr><td><code>hyva.formatPrice()<\/code><\/td><td>Formats a numerical value as a currency string based on store settings.<\/td><\/tr><tr><td><code>hyva.replaceDomElement()<\/code><\/td><td>Replaces an existing DOM element with new HTML content.<\/td><\/tr><tr><td><code>hyva.str()<\/code> \/ <code>hyva.strf()<\/code><\/td><td>Replaces placeholders in strings; useful for translations and dynamic text.<\/td><\/tr><tr><td><code>x-magento-init (Alpine.js)<\/code><\/td><td>Initializes Alpine.js components with Magento&#8217;s JSON config.<\/td><\/tr><tr><td><code>hyva.formValidation (Alpine.js)<\/code><\/td><td>Client-side form validation component.<\/td><\/tr><tr><td><code>window.dispatchMessages()<\/code><\/td><td>Displays Magento-style success, error, or info messages to the user.<\/td><\/tr><tr><td><code>BASE_URL<\/code>, <code>CURRENT_STORE_CODE<\/code><\/td><td>Global variables for constructing dynamic URLs.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">These helpers are not put in a dedicated .js file but are dynamically exposed to the global window object by the <code>hyva.phtml<\/code> template.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Breakdown of the Hyv\u00e4 JavaScript Helper Functions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">1. HyvaJsPriceUtils<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">It adds a <code>formatPrice()<\/code> method that takes numbers and adds them in a proper format as per the store&#8217;s settings (e.g., currency symbol, decimal places, thousands separator).<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\/\/ A simple way to format a price\nconsole.log(HyvaJsPriceUtils.formatPrice(10.50));\n\n\/\/ Passing additional options (optional)\nlet formattedPrice = HyvaJsPriceUtils.formatPrice(200.00, {\n    \/\/ Optionally override default formatting options\n});\nconsole.log(formattedPrice);\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">2. hyva.getFormKey()<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">This function is used for AJAX-based forms where you need to pass the form key along with your request data.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\/\/ Retrieve the form key\nconst form_key = hyva.getFormKey();\n\n\/\/ Log it to the console\nconsole.log(form_key);\n\n\/\/ You can now include this in your AJAX request payload\n\/\/ For example: { form_key: form_key, sku: 'my-product-sku' }\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">3. hyva.getCookie()<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>hyva.getCookie(name)<\/code> retrieves the value of any cookie by its name. It provides a clean and reliable way to access client-side data.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\/\/ Retrieve a cookie by name\nconst myCookieValue = hyva.getCookie('mage-cache-sessid');\n\n\/\/ Log the value\nconsole.log(myCookieValue);\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">4. hyva.replaceDomElement()<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The function correctly re-initializes any Alpine.js components within the new HTML, ensuring everything remains interactive.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\/\/ Select the element with ID 'cart-count' and replace its content\nconst newHtml = `\n    &lt;div x-text=\"itemCount\">&lt;\/div>\n`;\nhyva.replaceDomElement('#cart-count', newHtml);\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">5. window.dispatchMessages()<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">This function allows you to display system messages (e.g., success, error, warning) to the user via JavaScript.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\/\/ Dispatch a single success message\nwindow.dispatchMessages([\n    { type: 'success', text: 'Product successfully added to your cart!' }\n]);\n\n\/\/ Dispatch multiple messages (e.g., an error and a warning)\nwindow.dispatchMessages([\n    { type: 'error', text: 'An error occurred during the process.' },\n    { type: 'warning', text: 'Some items are low in stock.' }\n]);\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">6. hyva.setCookie()<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">This function allows you to easily set a cookie&#8217;s value, expiration, path, and other options.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\/\/ Set a simple cookie\nhyva.setCookie('my-app-state', 'active');\n\n\/\/ Set a cookie with a 7-day expiration (in milliseconds)\nconst oneWeekInMilliseconds = 7 * 24 * 60 * 60 * 1000;\nhyva.setCookie('user_preference', 'light-mode', { expires: oneWeekInMilliseconds });\n\n\/\/ Set a cookie with a specific path\nhyva.setCookie('session_data', '12345', { path: '\/' });\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">7. hyva.strf() (String Formatting for Translations)<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">This function is primarily used for formatting strings that contain placeholders, making it perfect for dynamic text and translations.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\/\/ Example of a formatted string from the backend\nconst translatedString = \"There are %s items in your cart.\";\n\/\/ Use hyva.strf() to replace the placeholder\nconst formattedMessage = hyva.strf(translatedString, 5);\nconsole.log(formattedMessage); \/\/ Output: \"There are 5 items in your cart.\"\n\n\/\/ You can also use it with multiple placeholders\nconst multiplePlaceholders = \"%s added %s to cart.\";\nconst multipleFormatted = hyva.strf(multiplePlaceholders, 'John', 'Product A');\nconsole.log(multipleFormatted); \/\/ Output: \"John added Product A to cart.\"\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">8. hyva.formValidation (Alpine.js)<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Hyv\u00e4 includes a reusable Alpine.js component for client-side form validation. By adding the <code>x-data=\"hyva.formValidation\"<\/code> attribute to a form, you can leverage standard HTML5 required attributes and other custom validation rules to provide real-time feedback to the user, preventing unnecessary server-side requests.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;form x-data=\"hyva.formValidation\" @submit.prevent=\"validate\">\n    &lt;div class=\"field mb-4\">\n        &lt;label for=\"name\" class=\"block text-gray-400 mb-1\">Your Name&lt;\/label>\n        &lt;input type=\"text\" id=\"name\" required class=\"w-full px-3 py-2 rounded-md bg-gray-700 border border-gray-600\">\n        &lt;span class=\"validation-error text-sm text-red-400 mt-1\">&lt;\/span>\n    &lt;\/div>\n    &lt;div class=\"field mb-4\">\n        &lt;label for=\"email\" class=\"block text-gray-400 mb-1\">Email&lt;\/label>\n        &lt;input type=\"email\" id=\"email\" required class=\"w-full px-3 py-2 rounded-md bg-gray-700 border border-gray-600\">\n        &lt;span class=\"validation-error text-sm text-red-400 mt-1\">&lt;\/span>\n    &lt;\/div>\n    &lt;button type=\"submit\" class=\"w-full bg-blue-600 text-white font-bold py-2 px-4 rounded-md hover:bg-blue-700 transition-colors duration-200\">Submit&lt;\/button>\n&lt;\/form>\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">9. BASE_URL, CURRENT_STORE_CODE (Global Variables)<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">For JavaScript code that needs to make API calls or reference dynamic URLs, the global <code>BASE_URL<\/code> and <code>CURRENT_STORE_CODE<\/code> variables are invaluable. They are automatically injected by Hyv\u00e4&#8217;s layout and provide reliable, consistent values for constructing paths regardless of the store&#8217;s configuration or base URL.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\/\/ Get the current store's URL\nconsole.log(BASE_URL); \/\/ e.g., \"[https:\/\/www.yourstore.com\/](https:\/\/www.yourstore.com\/)\"\n\n\/\/ Get the store code\nconsole.log(CURRENT_STORE_CODE); \/\/ e.g., \"en_us\"\n\n\/\/ Construct a dynamic URL for an API call\nconst myApiUrl = `${BASE_URL}rest\/${CURRENT_STORE_CODE}\/V1\/custom-endpoint`;\nconsole.log(myApiUrl); \/\/ e.g., \"[https:\/\/www.yourstore.com\/rest\/en_us\/V1\/custom-endpoint](https:\/\/www.yourstore.com\/rest\/en_us\/V1\/custom-endpoint)\"\n<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The Hyv\u00e4 JavaScript helper functions and integrated Alpine.js components are powerful assets for any Magento 2 developer working with the Hyv\u00e4 theme. By understanding and utilizing these tools, you can write more efficient, cleaner, and more robust frontend code. They abstract away much of the complexity of interacting with Magento&#8217;s frontend, allowing you to focus on building great user experiences with confidence.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Embrace these helpers in your next Hyv\u00e4 project and experience the difference they make!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this blog post, we have listed the most useful Hyv\u00e4 JavaScript helper functions, which are accessible via the global window.hyva object on every storefront&#8230;<\/p>\n","protected":false},"author":5,"featured_media":22298,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[5869],"tags":[],"class_list":["post-21805","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-hyva-themes"],"acf":[],"_links":{"self":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/21805","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/comments?post=21805"}],"version-history":[{"count":13,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/21805\/revisions"}],"predecessor-version":[{"id":22300,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/21805\/revisions\/22300"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/media\/22298"}],"wp:attachment":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/media?parent=21805"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/categories?post=21805"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/tags?post=21805"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}