Issues Triggering Javascript Function

Hi Folks,

This is my first time using javascript functions and I’m having a problem triggering the function.

I’m looking to add social sharing options to lots of pages on my website and want to use a javascript function to add the page information into the URL of the link. The code works if I go into inspector and trigger it manually, however doesn’t work automatically on page load.

This is all implemented on: 10 Bat Coloring Pages (Free Printable PDFs)
And my netlify site name is: lovely-semifreddo-4bea40

I’d be very grateful for any help!

Here’s an example of the social media link:

share on facebook

Here’s an example of the javascript:

window.onload = function() {
console.log(“Social share script is running”); // Debugging log

try {
var currentURL = window.location.href;
var textToShare = encodeURIComponent(“Check out this article!”);

// Facebook
var facebookLink = document.querySelector('[data-social-id="facebook-share"]');
if (facebookLink) {
  facebookLink.href = `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(currentURL)}`;
  console.log("Facebook link updated");
} else {
  console.warn("Facebook link not found");
}

} catch (error) {
console.error(“An error occurred in the social share script:”, error);
}
};

Hi @mattbipbapbop, I’m going to move this to the open talk category as this is something outside of the scope of support we can provide. (We handle all things Netlify related here :slight_smile: )

Though here is a pointer to get you going,

I’d definitely recommend using an event listener over window.onload… much more reliable for all use cases.

document.addEventListener('DOMContentLoaded', initializeSocialSharing);
window.addEventListener('load', initializeSocialSharing);

All the best,