Open button links in new tab

I can’t figure out how to make an external link within a button open in a new tab, and I don’t see anyone else asking about this either. Anyone willing to help?

<script>
const externalLinks = document.querySelectorAll('a[href^="http"]:not([href^="https://demosite.com"])');
externalLinks.forEach(link => {
  link.target = '_blank';
});
<script>

The code above will open all links that don’t go to demosite.com in a new link. (Update for your site, obviously.)

To target a single button, you’re going to need to figure out how to select it. Most ghost buttons are actually ‘a’ tags, so making that selector a.kg-header-card-button for example would let you select for just header card buttons. Or a.kg-btn for buttons in the body of a post… or…

3 Likes

Hey that worked, Thank you so much!

1 Like

This code works for Link and Button:

<script>
document.addEventListener('DOMContentLoaded', function() {
  // Target external links
  var extLinks = document.querySelectorAll('a[href*="://"]'); // Select links with external URLs
  for (var i = 0; i < extLinks.length; i++) {
    if (!extLinks[i].href.startsWith(window.location.origin)) { // Exclude busynesspro.com links
      extLinks[i].setAttribute('target', '_blank');
    }
  }

  // Target buttons (assuming they lead somewhere external)
  var buttons = document.querySelectorAll('button');
  for (var i = 0; i < buttons.length; i++) {
    if (!buttons[i].hasAttribute('href')) { // Only target buttons without href attribute (likely for internal navigation)
      buttons[i].setAttribute('target', '_blank');
    }
  }
});
</script>