By default, social media links in the Divi theme open in the same window. If you built a website with a Divi theme and added social icons/links to it, you’ll notice that they are not opening in a new tab. That means, if someone clicks any of the social links, the visitor is leaving your website.
But if you want your visitors to open the social media links without leaving your website, you have to add a target=”_blank” to all the social media links. And you have to do it using JavaScript.
How to open social media links in a new tab in the Divi theme?
Copy & paste the following code to “Divi → Theme Options → Integration → Add code to the < body > (good for tracking codes such as google analytics)”
<script>
const sociaLinks = document.querySelectorAll(".et-social-icons .et-social-icon a");
for (let i = 0; i < sociaLinks.length; i++) {
sociaLinks[i].setAttribute("target", "_blank");
}
</script>
This is pure/vanilla JavaScript and you don’t even need to use/load the huge jQuery library to accomplish the simple task. This JavaScript code is wrapped by HTML “<script>” tag so you can use the JS code directly to the HTML file.
Copy & paste the exact same code as you see above.
Code explanation
There is nothing crazy going on with this JavaScript. querySelectorAll represents all the elements by the CSS selector. In our example, the selector is “.et-social-icons .et-social-icon a” and these are CSS class names created by Divi. If you inspect the element in your browser, you’ll find that all the social media links are wrapped by these two class names.
Using the setAttribute, we’re adding an extra HTML attribute to the anchor tags (links) which is target=”_blank”
“for” is a loop and we are telling the browser to keep adding the target=”_blank” attribute to the links (social) until it finishes the total link counts. That’s it!
Conclusion
I came across this situation many times before. After a long period, recently built a WordPress website using the Divi theme and encountered the same issue again.
I found a lot of documentation to achieve my goal which is opening the social media links in a new tab. But all of them were written in jQuery. So I wrote my own code with only JavaScript. And I thought it would be helpful for others if I share this code & technic.
In my opinion, you really need to load the jQuery library to accomplish this task. Also, using too many 3rd party libraries may slow down your website.