Share Selected Text On Twitter

Category: Javascript , Social Media | September 11, 2019
Author: Coding Journey
Views Total: 15
Official Page: Go to website
Last Update: September 11, 2019
License: MIT

Preview:

Share Selected Text On Twitter

Description:

Yet another script that allows the visitor to select and share any part of your text content on Twitter.

How to use it:

Add the CSS class selectable-text-area to the text blocks.

<div class="selectable-text-area">
  Any Content Here
</div>

Apply CSS styles to the floating Twitter share icon above the ext selection.

#twitter-share-btn {
  width: 2.5rem;
  height: 2.5rem;
  font-size: 1.25rem;
  color: #56b8f5;
  background-color: #fff;
  cursor: pointer;
  border: 2px solid #56b8f5;
  border-radius: 50%;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 10;
  display: none;
  transition: color 0.2s, background-color 0.2s ease-in-out;
}

#twitter-share-btn:hover {
  color: #fff;
  background-color: #56b8f5;
}

#twitter-share-btn i {
  pointer-events: none;
}

.btnEntrance {
  animation-duration: 0.2s;
  animation-fill-mode: both;
  animation-name: btnEntrance;
}

@keyframes btnEntrance { /* zoomIn */
  0% {
    opacity: 0;
    transform: scale3d(0.3, 0.3, 0.3);
  }
  100% {
    opacity: 1;
  }    
}

Include the Font Awesome for the Twitter icon.

<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.2/css/all.min.css'>

The main JavaScript.

const selectableTextArea = document.querySelectorAll(".selectable-text-area");
const twitterShareBtn = document.querySelector("#twitter-share-btn");

selectableTextArea.forEach(elem => {
  elem.addEventListener("mouseup", selectableTextAreaMouseUp);
});

twitterShareBtn.addEventListener("click", twitterShareBtnClick);

document.addEventListener("mousedown", documentMouseDown);

function selectableTextAreaMouseUp(event) {
  setTimeout(() => {// In order to avoid some weird behavior...
    const selectedText = window.getSelection().toString().trim();
    if (selectedText.length) {
      const x = event.pageX;
      const y = event.pageY;
      const twitterShareBtnWidth = Number(getComputedStyle(twitterShareBtn).width.slice(0, -2));
      const twitterShareBtnHeight = Number(getComputedStyle(twitterShareBtn).height.slice(0, -2));

      if (document.activeElement !== twitterShareBtn) {
        twitterShareBtn.style.left = `${x - twitterShareBtnWidth * 0.5}px`;
        twitterShareBtn.style.top = `${y - twitterShareBtnHeight * 1.25}px`;
        twitterShareBtn.style.display = "block";
        twitterShareBtn.classList.add("btnEntrance");
      } else
      {
        twitterShareBtn.style.left = `${x - twitterShareBtnWidth * 0.5}px`;
        twitterShareBtn.style.top = `${y - twitterShareBtnHeight * 0.5}px`;
      }
    }
  }, 0);
}

function documentMouseDown(event) {
  if (event.target.id !== "twitter-share-btn" && getComputedStyle(twitterShareBtn).display === "block") {
    twitterShareBtn.style.display = "none";
    twitterShareBtn.classList.remove("btnEntrance");
    window.getSelection().empty();
  }
}

function twitterShareBtnClick(event) {
  const selectedText = window.getSelection().toString().trim();
  if (selectedText.length) {
    // General Twitter Share URL: https://twitter.com/intent/tweet?text={title}&url={url}&hashtags={hash_tags}&via={user_id}
    const twitterShareUrl = "https://twitter.com/intent/tweet";
    const text = `${encodeURIComponent(selectedText)}`;
    const currentUrl = encodeURIComponent(window.location.href);
    const hashtags = "helloworld, test, testing";
    const via = "CodingJrney";
    window.open(`${twitterShareUrl}?text="${text}"&url=${currentUrl}&hashtags=${hashtags}&via=${via}`);

    // Alternatively, we could include everything in the "text" field -> more room to customize the tweet:
    // window.open(`${twitterShareUrl}?text="${text}" by @${via} ${hashtags.split(",").map(h => "%23"+h.trim()).join(" ")} ${currentUrl}`);

    // We could also specify new window features:
    // const newWindowOptions = "height=400,width=550,top=0,left=0,resizable=yes,scrollbars=yes";
    // window.open(`${twitterShareUrl}?text="${text}"&url=${currentUrl}&hashtags=${hashtags}&via=${via}`, "ShareOnTwitter", newWindowOptions);
  }
}

You Might Be Interested In:


Leave a Reply