Toby Cook Toby Cook - 1 year ago 71
HTML Question

jQuery - Links Stop Working After Page Resize

I am trying to make my website responsive and have added some jQuery to remove and insert HTML. I am trying to display a popup box when an anchor tag around an image is clicked.

The window appears the first time the page is loaded, but when it has been resized the link no longer works and doesn't display the popup.

// Call hidePopup function upon clicking element with class ".close"
$(function() {
$('.close').click(hidePopup);
});
function hidePopup() {
if (this.id == 'hideP1') {
$('#popup1').addClass('hidePopups');
} else if (this.id == 'hideP2') {
$('#popup2').addClass('hidePopups');
} else if (this.id == 'hideP3') {
$('#popup3').addClass('hidePopups');
}
}

// Call showPopup function upon clicking element with class ".imgClick"
$(function() {
$('.imgClick').click(showPopup);
});
function showPopup() {
if (this.id == 'imgEms') {
$('#popup1').removeClass('hidePopups');
} else if (this.id == 'imgPas') {
$('#popup2').removeClass('hidePopups');
} else if (this.id == 'imgTs') {
$('#popup3').removeClass('hidePopups');
}
}
var LinkedHtml = [
'<a href="#popup1" class="imgClick" id="imgEms" onclick="showPopup()"><img src="assets/img/festival-big.jpg" title="Event Medical Services"></a>',
'<a href="#popup2" class="imgClick" id="imgPas" onclick="showPopup()"><img src="assets/img/ambulance2.png" title="Private Ambulance Services"></a>',
'<a href="#popup3" class="imgClick" id="imgTs" onclick="showPopup()"><img src="assets/img/training_1.jpeg" title="Training Solutions"></a>'
];
var nonLinkedHtml = [
'<img src="assets/img/festival-big.jpg" title="Event Medical Services" id="emsImg">',
'<img src="assets/img/ambulance2.png" title="Private Ambulance Services" id="pasImg">',
'<img src="assets/img/training_1.jpeg" title="Training Solutions" id="tsImg">'
];

$(window).resize(function() {
windowSize = $(window).width();
var anchorIds = ['#imgEms','#imgPas','#imgTs'];
var imageIds = ['#emsImg','#pasImg','#tsImg'];

if (windowSize < 740) {
for (var i = 0; i < imageIds.length; i++) {
$(imageIds[i]).replaceWith(LinkedHtml[i]);
}
} else if (windowSize > 740) {
$(".overlay").addClass("hidePopups");
for (var i = 0; i < anchorIds.length; i++) {
$(anchorIds[i]).replaceWith(nonLinkedHtml[i]);
}
}
});


I do not have much experience with JavaScript nor jQuery and I have been struggling with this issue all day.

Thank you!

Answer Source

What happens if you try to use a delegate instead?

$(function() {
    $(document.body).on('click', '.imgClick', showPopup);
});

If this works, then you should try to find a parent element that always exists for the imgClick elements, that is never replaced, and use that as a selector instead of document.body.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download