DEV Community

Cover image for Create a Click-To-Tweet Widget With JavaScript
Ewomazino Akpareva
Ewomazino Akpareva

Posted on

Create a Click-To-Tweet Widget With JavaScript

Hello guys,
Today is a good day for an amazing JavaScript article and I am going to show you how to create a Click-to-Tweet widget that can be added to your website or web app.

Interestingly, this is one of the projects I teach in my new 100Days of JavaScript Course which I created to help beginners/intermediate level JavaScript developers sharpen their JavaScript skills. Feel free to check it out.

What is this Click-To-Tweet widget of which I speak?
Well, it’s a simple widget you can have on your website with pre-defined content which your user can easily share on Twitter.
This can be a good way to encourage your users to talk about your product or service on social media.

Getting Started!!!
To get started we are going to create a form with a textarea and a tweet button.
We are also going to place a number beside the button which would contain the maximum tweet character counter that updates as the user types into the textarea.
Also, note that we use bootstrap 5 to make our work easier.

Here is the Markup

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script
      src="https://kit.fontawesome.com/1935d064dd.js"
      crossorigin="anonymous"
    ></script>
    <!-- CSS only -->
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6"
      crossorigin="anonymous"
    />
    <link rel="stylesheet" href="styles.css" />
  </head>
  <body>
    <div class="container">
      <div class="row box">
        <div class="col-md-6">
          <p>Share this on Twitter.</p>
          <form action="">
            <textarea cols="30" rows="5" class="form-control fs-5">
Hello</textarea
            >
            <div
              class="button d-flex justify-content-end align-items-center mt-2"
            >
              <span class="limit px-3 fs-4">80</span>
              <button class="btn btn-primary">Tweet</button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <script src="script.js"></script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Here is the CSS

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
html {
  font-size: 10px;
}

body {
  font-family: "Open Sans", sans-serif;
  background-color: #eee;
}

p {
  font-size: 1.6rem;
  line-height: 1.5;
}

.container {
  max-width: 900px;
  margin: 0 auto;
  padding: 0 20px;
}

/* Start Here */
.box {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}
Enter fullscreen mode Exit fullscreen mode

Here is our Page

Alt Text

Now it's time for the JavaScript Logic for our click-to-tweet widget.

There are two scenarios for this app;

  1. Textarea with predefined content that CAN be changed by the user.
  2. Textarea (disabled) predefined content that CANNOT be changed by the user. The difference between both options is “the addition of a disabled attribute” to the textarea.

Next, let’s outline what we want to achieve and how we want our app to behave as the user interacts with it.

  1. Set a max character limit for the textarea.
  2. Update the character limit on the page as the user types in the textarea.
  3. Change the character limit color from black to red when the user exceeds it.
  4. Disable the tweet button when the user exceeds the max character limit.
  5. When the user clicks the tweet button, open a new tab(twitter.com) and transfer the content of the textarea to a new tweet box.

Now let’s get into the code.
First, we are going to create variables that would target the textarea, the limit class, and the button, then we are going to create a max variable and set it to 60.

const input = document.querySelector("textarea");
const btn = document.querySelector(".btn");
const limit = document.querySelector(".limit");
let max = 60;
Enter fullscreen mode Exit fullscreen mode

Next, we are going to create a function that would update the limit field when the user types into the textarea, effectively carrying out steps 1 - 4 listed above.

const updateLimit = () => {
  limit.textContent = max;
  input.addEventListener("input", () => {
    let inputLength = input.value.length;
    limit.textContent = max - inputLength;
    if (inputLength > max) {
      btn.disabled = true;
      limit.style.color = "red";
    } else {
      btn.disabled = false;
      limit.style.color = "black";
    }
  });
};
updateLimit();
Enter fullscreen mode Exit fullscreen mode

Next, let's add an event listener on the tweet button that would call a tweet function. To do this last bit, you need to read Twitter developer docs.

btn.addEventListener("click", (e) => {
  e.preventDefault();
  tweet();
});

const tweet = () => {
  let tweetInput = "https://twitter.com/intent/tweet?text=";
  window.open(`${tweetInput}${input.value}`);
};
Enter fullscreen mode Exit fullscreen mode

Here is the final code

const input = document.querySelector("textarea");
const btn = document.querySelector(".btn");
const limit = document.querySelector(".limit");
let max = 60;

const updateLimit = () => {
  limit.textContent = max;
  input.addEventListener("input", () => {
    let inputLength = input.value.length;
    limit.textContent = max - inputLength;
    if (inputLength > max) {
      btn.disabled = true;
      limit.style.color = "red";
    } else {
      btn.disabled = false;
      limit.style.color = "black";
    }
  });
};
updateLimit();

btn.addEventListener("click", (e) => {
  e.preventDefault();
  tweet();
});

const tweet = () => {
  let tweetInput = "https://twitter.com/intent/tweet?text=";
  window.open(`${tweetInput}${input.value}`);
};
Enter fullscreen mode Exit fullscreen mode

And now we have our functional click-to-tweet widget.

Alt Text

Thanks for reading this tutorial.
if you enjoyed it, feel free to connect with me:
Website: ZinoTrustAcademy.com

Twitter: @ZinoTrust

YouTube: ZinoTrust Tutorials

Top comments (0)