Introduction
Being able to make a div tag container into a link is not a straight forward option unless you get into writing code.
In this experiment, I have created a script that will:
- look for all occurrences of the ‘container-link-outer’ class.
- For each match found, the script will look at the internal code and attempt to find a ‘container-link’ class containing a link.
- If found, an addEventListener method is added to the tag containing the ‘container-link-outer’ class.
- When a tag is clicked that has the the href parameter value holding the link address will applied to the window.location.href object property.
Example 1: Manual application
In this example, I have a (light blue) box and I want the entrire box including the internal elements to be a unified link. Most page builders will not allow this so but using Container Link, I can add the ‘container-link-outer’ to the outer container block, add a link to an internal item (in this case a button) and have the button link become a link for the whole section.
Heading for this section
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Dignissim sodales ut eu sem. I like vegan gummy lollies. Please don’t tell anyone. Sed risus pretium quam vulputate dignissim suspendisse. Pretium quam vulputate dignissim suspendisse in est ante in nibh. Viverra tellus in hac habitasse platea dictumst vestibulum.
Example 2: Inside the loop grid
Rendering cards as complete links has always been an issue. Mostly we create a link on the image, title and a button. If there are any spaces between the linked elements , the cursor would flicker between an arrow and a pointer.
By using the Container Link approach, you can apply the ‘container-link-outer’ class to the card (or outer container) and then add the ‘container-link’ class to an internal block that has a hyperlink. Save, refresh and now your whole card now behaves as a link. WIN!
Conclusion
document.querySelectorAll('.container-link-outer').forEach(function(outerContainer) {
const linkElement = outerContainer.querySelector('.container-link a');
if (linkElement) {
const href = linkElement.getAttribute('href');
const title = linkElement.getAttribute('title');
// Apply the href to the .container-link-outer
outerContainer.addEventListener('click', function() {
window.location.href = href;
});
// Set cursor to pointer if a link is found
outerContainer.style.cursor = 'pointer';
// Add title attribute to the .container-link-outer if found
if (title) {
outerContainer.setAttribute('title', title);
}
}
});