Event delegation with anchor href
by Amy L
HTML
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css">
<div class="container">
<a href="http://google.com" target="_blank" class="openNewWindow"
data-window-url="http://gooogle.com" data-window-params="width=750,height=550,top=100,left=100,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0">
<i class="fas fa-question-circle"></i>
</a>
</div>
CSS
.container {
background-color: #efefef;
}
JavaScript
function openNewWindow( url, windowproperties )
{
window.open( url, '', windowproperties );
}
(function (document) {
document.addEventListener('click', function(event) {
const clickedEl = getEl(event.target);
console.log(clickedEl);
if (clickedEl && clickedEl.className.indexOf('openNewWindow') !== -1) {
const url = clickedEl.dataset.windowUrl;
const windowProperties = clickedEl.dataset.windowParams;
openNewWindow(url, windowProperties);
return false;
}
});
function getEl(clickedEl) {
let foundEl;
if (clickedEl) {
while (!foundEl && clickedEl.tagName.toLowerCase() !== 'body') {
console.log('checking start', clickedEl)
if (clickedEl.className.indexOf('openNewWindow') !== -1) {
foundEl = clickedEl;
} else {
clickedEl = clickedEl.parentElement;
}
}
}
return foundEl;
}
})(document)