• Automatically Select First Tab and Content Loading – JavaScript – SitePoint Forums

    First, let’s put away some sins.

    Tab links should not use inline event attributes. This mixes up JavaScript with your HTML and is best avoided.

    Instead, remove these onmouseover inline event attributes:

    
    

    and let JavaScript do what it does best:

    const tablinks = document.querySelectorAll(".tablinks");
    tablinks.forEach(function addTabEvent(tab) {
        tab.addEventListener("mouseover", function tabMouseoverHandler(evt) {
            const serviceName = tab.innerText;
            openService(evt, tab.innerText);
        });
    });
    

    Since Wrongful Deaths has a different service name than Wrongful Accidents, we can add data to this tab and have the script code prefer to use that different data instead.

      
    
        tab.addEventListener("mouseover", function tabMouseoverHandler(evt) {
            const serviceName = tab.dataset.serviceName || tab.innerText;
            openService(evt, tab.innerText);
        });
    

    We can now check if the tab is the first tab in the list and fire the mousover event.

    // tablinks.forEach(function addTabEvent(tab) {
    tablinks.forEach(function addTabEvent(tab, index) {
        ...
        if (index === 0) {
            tab.dispatchEvent(new Event("mouseover"));
        }
    });
    

    Here is the extra script code to add, and don’t forget to remove those inline event attributes.

    const tablinks = document.querySelectorAll(".tablinks");
    tablinks.forEach(function addTabEvent(tab, index) {
        tab.addEventListener("mouseover", function tabMouseoverHandler(evt) {
            const serviceName = tab.dataset.serviceName || tab.innerText;
            openService(evt, tab.innerText);
        });
        if (index === 0) {
            tab.dispatchEvent(new Event("mouseover"));
        }
    });
    

    Comments are closed.