Container Link

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:

  1. look for all occurrences of the ‘container-link-outer’ class.
  2. For each match found, the script will look at the internal code and attempt to find a ‘container-link’ class containing a link.
  3. If found, an addEventListener method is added to the tag containing the ‘container-link-outer’ class.
  4. 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.

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);
            }
        }
    });

Related posts

A vertical scroll experiment combining Elementor, GSAP and Vanilla JS.

Leave a Reply

Your email address will not be published. Required fields are marked *