diff --git a/app/assets/javascripts/govuk_publishing_components/components/single-page-notification-button.js b/app/assets/javascripts/govuk_publishing_components/components/single-page-notification-button.js new file mode 100644 index 0000000000..2787eba3aa --- /dev/null +++ b/app/assets/javascripts/govuk_publishing_components/components/single-page-notification-button.js @@ -0,0 +1,43 @@ +/* global XMLHttpRequest */ +window.GOVUK = window.GOVUK || {} +window.GOVUK.Modules = window.GOVUK.Modules || {}; + +(function (Modules) { + function SinglePageNotificationButton ($module) { + this.$module = $module + this.basePath = this.$module.querySelector('[name="base_path"]').value + } + + SinglePageNotificationButton.prototype.init = function () { + var xhr = new XMLHttpRequest() + var url = '/api/personalisation/check-email-subscription?base_path=' + this.basePath + xhr.open('GET', url, true) + xhr.onreadystatechange = function () { + if (xhr.readyState === 4 && xhr.status === 200) { + var responseText = xhr.responseText + // if response text exists and is JSON parse-able, parse the response and get the button html + if (responseText && this.responseIsJSON(responseText)) { + var newButton = JSON.parse(responseText).button_html + var html = document.createElement('div') + html.innerHTML = newButton + // test that the html returned contains the button component; if yes, swap the button for the updated version + var responseHasButton = html.querySelector('.gem-c-single-page-notification-button') + if (responseHasButton) { + this.$module.outerHTML = newButton + } + } + } + }.bind(this) + xhr.send() + } + + SinglePageNotificationButton.prototype.responseIsJSON = function (string) { + try { + JSON.parse(string) + } catch (e) { + return false + } + return true + } + Modules.SinglePageNotificationButton = SinglePageNotificationButton +})(window.GOVUK.Modules) diff --git a/app/views/govuk_publishing_components/components/_single_page_notification_button.html.erb b/app/views/govuk_publishing_components/components/_single_page_notification_button.html.erb index e143b289b1..31b0393f58 100644 --- a/app/views/govuk_publishing_components/components/_single_page_notification_button.html.erb +++ b/app/views/govuk_publishing_components/components/_single_page_notification_button.html.erb @@ -10,6 +10,7 @@ wrapper_classes = %w(gem-c-single-page-notification-button govuk-!-display-none-print) wrapper_classes << shared_helper.get_margin_bottom classes = "govuk-body-s gem-c-single-page-notification-button__submit" + data_attributes[:module] = "single-page-notification-button" %> <% button_text = capture do %> <%= text %>