PageSourceSearch

https://bestforbritain.org/wp-content/plugins/chd-action-centre/assets/js/chdactions-script.js?ver=1790851424

js bestforbritain.org collected 2026-10-01 11:30:48 UTC 12,079 bytes, 310 lines download raw bytes

1function chd_action_scripts() {
2  (function($) {
3
4    // Populate anonymous ID from cookie for analytics identity stitching
5    var getCookie = function(name) {
6      var value = "; " + document.cookie;
7      var parts = value.split("; " + name + "=");
8      if (parts.length === 2) return parts.pop().split(";").shift();
9    };
10    
11    var anonId = getCookie('chd_anon_id');
12    if (anonId && $('#chd_anon_id').length) {
13      $('#chd_anon_id').val(anonId);
14    }
15
16    // Check if the keys object exists and contains pubkey for reCAPTCHA
17    if (typeof keys !== 'undefined' && keys.pubkey) {
18        // Recaptcha
19        var reCaptchaFocus = function() {
20            var head = document.getElementsByTagName('head')[0];
21            var script = document.createElement('script');
22            script.type = 'text/javascript';
23            script.src = 'https://www.google.com/recaptcha/api.js?render=' + keys.pubkey;
24            head.appendChild(script);
25        };
26
27        $('.submit-form input').one('focus', reCaptchaFocus);
28    }
29
30    $('input#postcode').change(function() {
31        var thisVal = $(this).val();
32        var pcValid = isValidUKPostcode(thisVal);
33        if (!pcValid) {
34            $('.country-field, .country-field .err-msg').show().attr('aria-hidden', false);
35        } else {
36            $('.country-field').hide().attr('aria-hidden', true);
37        }
38    });
39
40    $('input[name="gdpr_consent"]').change(function() {
41        if ($('.chd-consent').hasClass('err')) {
42            $('.chd-consent').removeClass('err');
43            $('.chd-consent .err-msg').remove();
44        }
45
46        if ($(this).attr('id') == 'chd-consent-no') {
47            $('.chd-warning').show().attr('aria-hidden', false);
48        } else {
49            $('.chd-warning').hide().attr('aria-hidden', true);
50        }
51    });
52
53    var fe = false;
54    var hostname = window.location.hostname;
55
56    $('.submit-form').submit(function(e) {
57        var email = $('#mail-address').val();
58        var name = $('#full-name').val();
59        var errors = [];
60
61        if (!name || !name.trim()) {
62            errors.push('name');
63        }
64        if (!email || !email.trim()) {
65            errors.push('email');
66        }
67
68        if (errors.length > 0) {
69            e.preventDefault();
70            // Hide all error messages first
71            $('.err-msg').hide();
72            // Show the most specific error message available
73            var errorKey = 'missing_' + errors.join('_');
74            var $specificErr = $('.err-msg.' + errorKey);
75            if ($specificErr.length) {
76                $specificErr.addClass('show').show();
77            } else {
78                $('.err-msg.missing').addClass('show').show();
79            }
80            $('.chd-action-form-container').addClass('err');
81            return;
82        } else {
83            $('.err-msg').hide().removeClass('show');
84            $('.chd-action-form-container').removeClass('err');
85        }
86
87        if (typeof grecaptcha !== 'undefined' && keys.pubkey) {
88            var thisForm = $(this);
89            $('.submit-form button').text('Submitting, please wait ...');
90            if (!fe) {
91                e.preventDefault();
92                grecaptcha.ready(function() {
93                    grecaptcha.execute(keys.pubkey, { action: 'submit' }).then(function(token) {
94                        $.ajax({
95                            type: "post",
96                            url: myAjax.ajaxurl,
97                            data: {
98                                action: "chd_action_validate_g",
99                                token: token
100                            },
101                            success: function(response) {
102                                // jQuery auto-parses a JSON response (wp_send_json sends
103                                // an application/json content type), so `response` is
104                                // already an object here. Only JSON.parse it when it is
105                                // still a string; parsing an object gives
106                                // "[object Object]" and throws, which killed the success
107                                // handler and left the form stuck on "Submitting, please
108                                // wait ..." without ever submitting.
109                                var responseData = (typeof response === 'string') ? JSON.parse(response) 
109: response;
110                                // Update the nonce input value with the new nonce.
111                                $('#chd_nonce').val(responseData.nonce);
112                                // The rest of your code follows...
113                                if (responseData.status == 'success' || hostname.includes("staging") || hostname.includes(".local")) {
114                                    fe = true;
115                                    $('.submit-form').submit();
116                                } else if (responseData.status == 'lowscore') {
117                                    $("html,body").animate({ scrollTop: 0 }, "slow");
118                                    $('<div class="err-msg"><h3>You have failed our bot protection. If you are a real human please contact us.</h3></div>').insertBefore($('.chd-action-form-container'));
119                                }
120                            },
121                            error: function(response) {
122                                $("html,body").animate({ scrollTop: 0 }, "slow");
123                                $('<div class="err-msg"><h3>Something went wrong, please try again. If it continues please contact us.</h3></div>').insertBefore($('.chd-action-form-container'));
124                            }
125                        });
126                    });
127                });
128            } else {
129                return;
130            }
131        } else {
132            // If reCAPTCHA is not defined, simply submit the form
133            return;
134        }
135    });
136
137
138    // Donation Bits
139    // If donation form exists
140
141    window.addEventListener('message', function(event) {
142      var eventDetails = event.data;
143      if(eventDetails.amount_in_pence) {
144        var output = eventDetails.metadata;
145        var metadata = JSON.parse(output);
146        $.ajax({
147          type : "post",
148          url : myAjax.ajaxurl,
149          data : {
150            action: "update_donation_amount",
151            amount_in_pence : eventDetails.amount_in_pence,
152            interval_unit : eventDetails.interval_unit,
153
154          },
155          success: function(response) {
156            if(response) {
157              response = response.trim();
158              if(response == 'success') {
159
160              }
161            }
162          }
163        });
164        //
165        // // Get the returnURL value
166        // var returnURL = new URL(metadata.ReturnURL);
167        //
168        // // Change the 'act' URL parameter to 'share'
169        // returnURL.searchParams.delete('act'); // delete the existing 'act' parameter
170        // // Change the 'act' URL parameter to 'share'
171        // returnURL.searchParams.append('act', 'share'); // append a new 'act' parameter with the value 'share'
172        //
173        // returnURL.searchParams.delete('complete'); // delete the existing 'act' parameter
174
175        // Add the parameters to the URL
176        // returnURL.searchParams.append('amount_in_pence', eventDetails.amount_in_pence);
177        // returnURL.searchParams.append('donated', 'true');
178        // returnURL.searchParams.append('interval_unit', eventDetails.interval_unit);
179        // window.location.href = returnURL.href;
180      }
181    }, false);
182
183
184    if($('.chd-petition-container').length) {
185
186      function fix_form() {
187        var formContainer = $('.chd-action-form-container');
188        var windowHeight = $(window).height();
189        var windowWidth = $(window).width();
190        var contentContainerHeight = $('.chd-action-content-container').height();
191        var petitionFormTopContainer = $('.chd-top-action-form-container');
192        var petitionContainer = $('.chd-petition-container');
193        var petitionContainerBottom = petitionContainer.outerHeight() + petitionContainer.offset().top - 120;
194        var containerOffset = formContainer.offset();
195
196        // Calculate social proof height so the sticky form never overlaps it
197        var socialProof = petitionFormTopContainer.find('.social-proof-counter').first();
198        var socialProofHeight = socialProof.length ? socialProof.outerHeight(true) : 0;
199
200        $(window).scroll(function() {
201          var scrollTop = $(window).scrollTop();
202          var scrollBottom = $(this).scrollTop() + $(this).outerHeight();
203          var formHeight = formContainer.outerHeight();
204          // Total height the right column needs (social proof + form)
205          var totalRightHeight = socialProofHeight + formHeight;
206
207          if(windowWidth > 991) {
208            windowWidth = $(window).width();
209            formContainer.width(petitionFormTopContainer.width() - 44);
210            $('.fixed-bottom-button-bar').hide();
211            if(totalRightHeight < contentContainerHeight) {
212              if(totalRightHeight + scrollTop >= contentContainerHeight) {
213                formContainer.removeClass('fixed').addClass('absolute');
214              }
215              else if(scrollTop >= containerOffset.top && (formHeight < windowHeight)) {
216                formContainer.addClass('fixed').removeClass('absolute');
217              }
218              else {
219                formContainer.removeClass('fixed absolute');
220              }
221            }
222          }
223          else {
224            formContainer.removeClass('fixed absolute');
225            formContainer.css('width', '100%');
226            var checkVisibility = scrollTop + windowHeight;
227            var containerBelow = containerOffset.top + formHeight;
228
229            if(checkVisibility > containerOffset.top && scrollTop < containerBelow) {
230              $('.fixed-bottom-button-bar').hide();
231            }
232            else {
233              $('.fixed-bottom-button-bar').show();
234            }
235
236            //$('.fixed-bottom-button-bar').toggle((checkVisibility < containerOffset.top) && (scrollTop < containerBelow));
237
238          }
239        });
240
241      }
242
243      $(window).resize(function() {
244        fix_form();
245      });
246
247
248      $(window).on('load', function() {
249        fix_form();
250        var iframe = $('.chd-action-donate-container #smartraise-embed iframe');
251        if(iframe.length && typeof sendArr !== 'undefined') {
252          iframe = iframe[0];
253          iframe.contentWindow.postMessage(sendArr, '*');
254        }
255      });
256
257    }
258
259    $('.fixed-bottom-button-bar .button').on('click', function(e) {
260      var href = $(this).attr('href');
261      if (href && href.charAt(0) === '#') {
262        var $target = $(href);
263        if ($target.length) {
264          e.preventDefault();
265          $('html, body').animate({ scrollTop: $target.offset().top - 20 }, 400);
266        }
267      }
268    });
269
270
271    $(document).on('click', '.chd-action-sharing-options li.custom a', function(e) {
272      var thisBtn = $(this);
273      var originalText = thisBtn.find('span').text();
274      e.preventDefault();
275      e.stopImmediatePropagation();
276      copyToClipboard(thisBtn.attr('href'));
277      thisBtn.addClass('active').find('span').text('Link copied!');
278      setTimeout(function() {
279        thisBtn.removeClass('active').find('span').text(originalText);
280      }, 3000);
281    });
282
283    function copyToClipboard(text) {
284      if (navigator.clipboard && navigator.clipboard.writeText) {
285        navigator.clipboard.writeText(text);
286      } else {
287        // Fallback for older browsers
288        var dummy = document.createElement('textarea');
289        document.body.appendChild(dummy);
290        dummy.value = text;
291        dummy.select();
292        document.execCommand('copy');
293        document.body.removeChild(dummy);
294      }
295    }
296
297    function isValidUKPostcode(postcode) {
298      // The pattern of UK postcode
299      const regex = /^([A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}|GIR ?0A{2})$/i;
300
301      return regex.test(postcode);
302    }
303
304
305  })(jQuery);
306}
307
308jQuery(document).ready(function() {
309  chd_action_scripts();
310})

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.