How to add custom copy alert in Javascript?

谁都会走 提交于 2021-01-29 19:52:16

问题


Hey am new web developer and am working on a project. I am working on a quote website. In that website you can copy the quotes.

To understand the question clearly Please visit my CodePen or run the below code https://codepen.io/Akash11166666/pen/JjRzqzp Or

<!DOCTYPE html>
<html>
<head>
    <link href="Find Status/css/style.css" rel="stylesheet" />
<style>
.pagable {
  display: flex;
  flex-direction: column;
  border: var(--pageable-border);
  background: var(--pageable-background);
}

.pagable .pagable-results {
  display: flex;
  flex-direction: column;
  flex: 1;
  padding: 0.25em;
}

.pagable .pagable-status {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  padding: 0.25em;
  background: var(--pageable-status-background);
}

.pagable .pagable-actions {
  display: grid;
  grid-auto-flow: column;
  grid-gap: 0.25em;
}

.pagable .pagable-actions input[name="page-curr"] {
  width: 3em;
}
</style>
</head>
<body>
    <a href="hindinj.html">caeman</a>
  <div class="mainStatus">
   <h2 class="statusHeading">Latest English Status</h2>
 
 
 
 
 
 <div class="allquotes"></div>
<div class="pagable-status">
  <label>Page <span class="page-no-curr">1</span> of <span class="page-no-count">1</span></label>
  <div class="pagable-actions">
    <button class="page-btn-first">&#x226A;</button>
    <button class="page-btn-prev">&#60;</button>
    <input type="number" name="page-curr" min="1" value="1" />
    <button class="page-btn-next">&#62;</button>
    <button class="page-btn-last">&#x226B;</button>
    <select name="page-size">
      <option>20</option>
      <option>10</option>
      <option>20</option>
    </select>
  </div>
  <label>(<span class="result-count"></span> items)</label>
</div>

<script>
const resultEl = document.querySelector('.allquotes');
const pageSize = document.querySelector('select[name="page-size"]');
const pageCurr = document.querySelector('input[name="page-curr"]')
const resultCount = document.querySelector('.result-count')
const pageNoCurr = document.querySelector('.page-no-curr');
const pageNoCount = document.querySelector('.page-no-count')
const btnFirst = document.querySelector('.page-btn-first');
const btnPrev = document.querySelector('.page-btn-prev');
const btnNext = document.querySelector('.page-btn-next');
const btnLast = document.querySelector('.page-btn-last');

let results = [];

const getResultCount = () => results.length;
const getPageSize = () => +pageSize.value;
const getCurrPage = () => +pageCurr.value;
const getPageCount = () => Math.ceil(getResultCount() / getPageSize());

const pageResponse = (records, pageSize, page) =>
  (start => records.slice(start, Math.min(records.length, start + pageSize)))
  (pageSize * (page - 1));

const main = async() => {
  btnFirst.addEventListener('click', navFirst);
  btnPrev.addEventListener('click', navPrev);
  btnNext.addEventListener('click', navNext);
  btnLast.addEventListener('click', navLast);
  pageSize.addEventListener('change', changeCount);

  results = await retrieveAllQuotes();
  updatePager(results);
  redraw();
};
const redraw = () => {
  resultEl.innerHTML = '';
  const paged = pageResponse(results, getPageSize(), getCurrPage());
  const contents = document.createElement('div');
  contents.innerHTML = paged.map(record => `<div class='latestatus'><p class='copytxt'>${record.status}</p><div> <button class="copystatus btn">Copy</button></div></div>`).join('');
  resultEl.append(contents);
};

const navFirst = (e) => {
  pageNoCurr.textContent = 1;
  pageCurr.value = 1;
  redraw();
}

const navPrev = (e) => {
  const pages = getPageCount();
  const curr = getCurrPage();
  const prevPage = curr > 1 ? curr - 1 : curr;
  pageCurr.value = prevPage;
  pageNoCurr.textContent = prevPage;
  redraw();
}

const navNext = (e) => {
  const pages = getPageCount();
  const curr = getCurrPage();
  const nextPage = curr < pages ? curr + 1 : curr;
  pageCurr.value = nextPage;
  pageNoCurr.textContent = nextPage;
  redraw();
}

const navLast = (e) => {
  pageNoCurr.textContent = getPageCount();
  pageCurr.value = getPageCount();
  redraw();
}

const changeCount = () => {
  updatePager();
  redraw();
};

const updatePager = () => {
  const count = getPageCount();
  const curr = getCurrPage();
  pageCurr.value = curr > count ? 1 : curr;
  pageNoCurr.textContent = curr > count ? 1 : curr;
  pageNoCount.textContent = count;
  resultCount.textContent = getResultCount();
};

const retrieveAllQuotes = async function() {
  // here we are making a network call to your api
  const response = await fetch('Find Status/stat.php');
  
  // then converting it to json instead of a readable stream
  const data = await response.json();
  
  return data;
}
document.querySelector('.allquotes').addEventListener(
  'click',
  function (e) {
    e.preventDefault();
    if (e.target && e.target.matches('.copystatus')) {
        const quote = e.target.parentNode.closest('.latestatus')
            .childNodes[0].textContent;
        const textArea = document.createElement('textarea');
        textArea.value = quote;
        document.body.appendChild(textArea);
        textArea.select();
        document.execCommand('Copy');
        textArea.remove();
    }
  },
  false
);

main();
 
  

</script>
</body>
</html>

As you can see there are copy button for every quote (they are created from Javascript). They work perfectly but we cannot know is the text is copied. I needed a <span>Copied</span> to be visible when the copy button is clicked without inserting the <span> element in html that is creating it from Javascript. I tried to create span elements from Javascript but it is not working.

 copyAlertElement = document.createElement('span');
    copyAlertElement.classList.add('status-copy-alert')
    let copyMessage = document.createTextNode('Copied!');
    copyAlertElement.appendChild(copyMessage);

    element.appendChild(copyAlertElement);
    setTimeout(function() {
      element.removeChild(copyAlertElement);
    }, 700);

Again I will tell my problem that, I need a span element to be visible when the copy button is clicked. Without inserting span element directly to html that is, creating it from javascript

I heartly thanks those who answer this question


回答1:


copyAlertElement must be inserted under the body tag.




回答2:


This has several different ways to indicate the text has been copied

// create some sample data and a little list to test with
let list = document.getElementById("list");
let quotes = ['one', 'two', 'three', '4 four'];
let quoteBlock = document.getElementById("quote");
for (q of quotes) {
  let li = document.createElement("li");
  let span = document.createElement("span");
  span.classList.add("quote");
  let text = document.createTextNode(q);
  span.appendChild(text);
  li.appendChild(span);
  let button = document.createElement("button");
  button.textContent = "copy";
  li.appendChild(button);
  list.appendChild(li);
}

// this event listener will catch all the clicks on the list
list.addEventListener("click", evt => {
  // use CSS to inject the text (copied)
  let quoteParentEl = evt.target.parentNode; // get the li
  let quoteEl = quoteParentEl.querySelector(".quote"); // get the quote element
  quoteEl.classList.add("copied"); // add the copied CSS

  // create a span to add the word copied
  let span = document.createElement("span");
  span.textContent = " copied";
  quoteParentEl.appendChild(span); // add the span to the li

  // change the button text to indicate the quote was copied
  let buttonEl = evt.target; // get the button
  buttonEl.textContent = "copied";

  // display the quote text to confirm it wsa properly collected
  quoteBlock.textContent = quoteEl.textContent;
});
#list li {
  list-style-type: none;
}

#list li .quote {
  display: inline-block;
  width: 250px;
}

.copied {
  background-color: #999;
}

.copied::after {
  content: " (copied) ";
  animation: fadeOut ease 1s;
  animation-iteration-count: 1;
  animation-fill-mode: forwards;
}

@keyframes fadeOut {
0% {opacity:1;}
100% {opacity:0;}
}
<ul id="list">
</ul>

<blockquote id="quote"></blockquote>


来源:https://stackoverflow.com/questions/65839287/how-to-add-custom-copy-alert-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!