DanonymousCoder / Random-quotes-generator

A web app that generates random quotes
MIT License
4 stars 7 forks source link

Improve copyQuote Function #22

Closed subnetmasked closed 5 days ago

subnetmasked commented 1 week ago

This pull request improves the copyQuote function in the assets/js/script.js file. The changes enhance functionality, improve readability, and add better error handling. Here are the specific improvements made:

  1. Early Return:

    • The function now returns early if the quote is the default message ("Your quote will appear here..."). This improves readability and ensures that unnecessary operations are avoided.
  2. Removed Unnecessary Return Values:

    • The return values 1 and 0 have been removed as they were not used anywhere in the code. This simplifies the function.
  3. Clipboard API Support Check:

    • Added a check to see if the Clipboard API is supported by the browser. If not, an alert is displayed to inform the user, and the function returns early. This ensures compatibility with browsers that do not support the Clipboard API.
  4. Promise Handling:

    • The function now uses .then() and .catch() to handle the promise returned by navigator.clipboard.writeText. This provides better error feedback to the user and logs any errors to the console.

Code Changes:

function copyQuote() {
  const quote = quoteText.innerText; // Extract the quote from the div

  // Check if the quote is the default message
  if (quote === "Your quote will appear here...") {
    alert('Generate a quote first'); // Alert the user to generate a quote
    return; // Early return if the default message is displayed
  }

  // Check if the Clipboard API is supported
  if (!navigator.clipboard) {
    alert('Clipboard API not supported'); // Alert the user if Clipboard API is not supported
    return; // Early return if Clipboard API is not supported
  }

  // Copy the quote to the clipboard and handle the promise
  navigator.clipboard.writeText(quote)
    .then(() => {
      alert("Quote Copied"); // Alert the user on successful copy
    })
    .catch(err => {
      console.error('Failed to copy: ', err); // Log the error to the console
      alert('Failed to copy quote'); // Alert the user on failure to copy
    });
}
subnetmasked commented 5 days ago

Awesome!

Glad you found it useful for your project, friend! 💯

DanonymousCoder commented 5 days ago

Don't forget to star the repo!!! and create more issues

subnetmasked commented 5 days ago

Don't forget to star the repo!!! and create more issues

Sure thing! Feel free to send me an email or contact me on keybase if there's something specific you want to discuss about your project, or just banter about nerdy stuff 🥸 Contact info is on my Github profile

DanonymousCoder commented 4 days ago

Sure, would love to banter🫠