I have a script that triggers a "Leaving Site Alert" popup, if the link is an external link that isn't included in a list of allowed domains. The first link clicked always works correctly, but the subsequent links, trigger the popup correctly - but bring users to the first link. Trying to figure out why that's happening.
The jquery (with a little injected hubl) controlling the popup can be found below.
$(window).on("load", function() {
const popup = $('.alert-popup-container');
const domains = [];
// populate whitelisted domains array - **fyi this is written in hubl**
{% for item in module.domains %}
domains.push("{{ item }}");
{% endfor %}
function confirm (link) {
popup.addClass('active');
$('.popup-cancle, .alert-popup-close').click(function(e){
e.preventDefault();
popup.removeClass('active');
return true;
});
$('.popup-proceed').click(function(e){
e.preventDefault();
window.open(link, "_blank");
popup.removeClass('active');
return true;
});
}
$('a').on('click', function(e){
const target = $(this),
href = target.attr("href");
var trigger_alert = true;
// make sure url is not relative
if (href.indexOf('://') !== -1) {
for (var i = 0; i < domains.length; i++) {
if (href.indexOf(domains[i]) != -1) {
trigger_alert = false; // don't trigger the alert
}
}
if (trigger_alert) {
e.preventDefault();
confirm(target.attr("href"));
}
}
});
});
Here's the alert popup html:
<div class="alert-popup-container">
<div class="alert-popup">
<div class="alert-popup-close"></div>
{{ module.alert_text }}
<div class='controls'>
<div class="btn1">
<a href="#" class='cta_button popup-proceed'>Okay</a>
</div>
<div class="btn2">
<a href="#" class='cta_button popup-cancle'>Cancel</a>
</div>
</div>
</div>
</div>
The issue was that I have a click event inside another click event, which is causing the strange behavior. The issue was fixed by using jQuery's off() method. What this does is removes the previous click event, assigned when the first button was clicked.
Complete code:
$(window).on("load", function() {
const popup = $('.alert-popup-container');
const domains = [];
// populate whitelisted domains array - **fyi this is written in hubl**
{% for item in module.domains %}
domains.push("{{ item }}");
{% endfor %}
function confirm (link) {
popup.addClass('active');
$('.popup-cancle, .alert-popup-close').off().click(function(e){ // added off() here
e.preventDefault();
popup.removeClass('active');
return true;
});
$('.popup-proceed').off().click(function(e){ // and here
e.preventDefault();
window.open(link, "_blank");
popup.removeClass('active');
return true;
});
}
$('a').on('click', function(e){
const target = $(this),
href = target.attr("href");
var trigger_alert = true;
// make sure url is not relative
if (href.indexOf('://') !== -1) {
for (var i = 0; i < domains.length; i++) {
if (href.indexOf(domains[i]) != -1) {
trigger_alert = false; // don't trigger the alert
}
}
if (trigger_alert) {
e.preventDefault();
confirm(target.attr("href"));
}
}
});
});