no_idea_chris
New Coder
Hello and thank you for allowing me to join.
I have some code (below) for my site that someone linked me to.
It allows a clickthrough to open up in a new window. But i would like it to open in the same window /tab.
I have tried changing stuff but it just doesn't seem to do anything except get rid of the hover feature.
I am a complete novice!
If anyone could help and possibly give a short explanation as to why?
Thank you
I have some code (below) for my site that someone linked me to.
It allows a clickthrough to open up in a new window. But i would like it to open in the same window /tab.
I have tried changing stuff but it just doesn't seem to do anything except get rid of the hover feature.
I am a complete novice!
If anyone could help and possibly give a short explanation as to why?
Thank you
JavaScript:
<script>
(function () {
// The amount of time in milleseconds to intialize the code.
// This allows other code to run before our code is initialized.
const DELAY = 500;
/*********************************************************************
* DO NOT ALTER CODE BELOW THIS LINE UNLESS YOU KNOW WHAT YOU'RE DOING
*********************************************************************/
// Initialize after the page has been loaded
if (document.readyState === 'complete') {
setTimeout(init, DELAY)
} else {
document.addEventListener("DOMContentLoaded", function () {
setTimeout(init, DELAY);
}, false);
}
async function init() {
try {
const ids = await getItemsIds();
document.querySelectorAll('#thumbnails .thumb, #slideshow .slide').forEach(thumb => {
const img = thumb.querySelector('img');
const id = thumb.getAttribute('data-slide-id');
// Create and set title of thumbnail
if (img) {
thumb.setAttribute('data-thumb-title', img.alt);
}
// Create and set clickthrough url attribute
if (ids[id]) {
thumb.setAttribute('data-clickthrough-url', ids[id])
}
});
// Add click event that sends opens up browser in a new tab
document.addEventListener('click', evt => {
const thumb = evt.target.closest('.thumb, .slide');
if (thumb && thumb.getAttribute('data-clickthrough-url')) {
window.open(thumb.getAttribute('data-clickthrough-url'));
}
});
} catch (error) {
console.log('Error', error);
}
}
/**
* Creates on object mapping of slide id's and their associated clickthrough urls.
* @returns object
* @example
* {
* '45s329gdds0322343fs': 'https:/www.example.com',
* }
*/
async function getItemsIds() {
const url = new URL(window.location.href);
url.searchParams.set('format', 'json');
try {
const res = await fetch(url.toString());
let { items } = await res.json();
items = items || [];
const ids = items.reduce((obj, item) => {
if (!obj[item.id]) {
obj[item.id] = item.clickthroughUrl
}
return obj;
}, {});
return ids;
} catch (err) {
throw new Error(err);
}
}
})();
</script>
Last edited by a moderator: