Cover Image for How to add a WhatsApp share button in a website using JavaScript
116 views

How to add a WhatsApp share button in a website using JavaScript

To add a WhatsApp share button to a website using JavaScript, you can create a link with a href attribute that includes the WhatsApp share URL. Here’s an example:

HTML:

HTML
<a id="whatsappShareButton" href="#">Share on WhatsApp</a>

JavaScript:

JavaScript
document.getElementById("whatsappShareButton").addEventListener("click", function() {
  var text = "Hello, check out this website!";
  var url = encodeURIComponent(window.location.href);
  var whatsappUrl = "https://api.whatsapp.com/send?text=" + text + "%20" + url;
  window.open(whatsappUrl);
});

In this example, the HTML code includes an <a> element with the ID "whatsappShareButton". When this link is clicked, it triggers the JavaScript code to open a new window with the WhatsApp share URL.

The JavaScript code attaches an event listener to the WhatsApp share button using addEventListener(). When the button is clicked, the callback function is executed.

Inside the callback function, you can customize the text variable to include the message you want to share on WhatsApp.

The window.location.href retrieves the current URL of the webpage and encodes it using encodeURIComponent().

Then, the whatsappUrl variable is constructed by concatenating the WhatsApp share URL (https://api.whatsapp.com/send?text=) with the encoded text and url values.

Finally, window.open(whatsappUrl) is used to open a new window or tab with the WhatsApp share URL, which will initiate the sharing process when the user interacts with the opened WhatsApp application or website.

By implementing this code, clicking on the “Share on WhatsApp” link will open a new window or tab with the WhatsApp application or website, pre-populating the message and URL to be shared.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS