1
votes

Hey am new web developer and am working on a quote website project.

Now to understand my question, Just see the below Javascript.

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.classList.add("allStatus");
  const quotes = paged.map((record) => `<div class='latestatus'><p class='copytxt'>${record.quotes}</p><div> <button class="copystatus btn">Copy</button><span class="status-copy-alert hidden" id="status-copy-alert">Copied!</span></div></div>`);
  const quoteGroupNumer = Math.ceil(quotes.length / 2);
  const groups = Array(quoteGroupNumer).fill('').map((value, index) => {
    const groupQuoteFirst = quotes[2 * index]; // 0, 2, 4, 6
    const groupQuoteSecond = quotes[2 * index + 1] || ''; // 1, 3, 5, 7

    return `<div class="flex">${groupQuoteFirst}${groupQuoteSecond}</div>`;
  });

  contents.innerHTML = groups.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('https://goodman456.000webhostapp.com/api.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 notify = e.target.nextSibling.closest('.status-copy-alert');
      
      notify.classList.toggle('hidden');
      setTimeout(() => {
  notify.classList.add('hidden');
}, 600);

        const textArea = document.createElement('textarea');

        textArea.value = quote;

        document.body.appendChild(textArea);

        textArea.select();

        document.execCommand('Copy');

        textArea.remove();

    }

  },

  false

);
main();

And notice this section in JavaScript

const retrieveAllQuotes = async function() {
  // here we are making a network call to your api
  const response = await fetch('https://goodman456.000webhostapp.com/api.php');
  
  // then converting it to json instead of a readable stream
  const data = await response.json();

  return data;
}

I use API to fetch the Quotes.

Now consider that we have 3 html pages namely hp.html, lo.html and tr.html . Now the hp.html is for happy quotes and lo.html is for love quotes and tr.html for trend quotes.

Now I need to use the above Javascript to these 3 pages. As you know these are different category. Is there any way so that I can use same script file for all the 3 pages (Because of storage problem) and only change the API links of different pages. In other words, I use same script for all pages but the API section will be changed. So is there any way so that I can use the same script and only change the API section.

I have tried many ways to solve this problem but none of them work. As am new to Javascript I don't know much about this.

I hartley thanks for those who answer this question.

2
Send a parameter here const retrieveAllQuotes = async function(quoteType) and your api link will change, based on the quoteType parameter, and call it from your html e.g - onClick(retrieveAllQuotes('loveQuote'))Dhiraj
Do you use a webserver? If so, which one? What is your server language? The problem is solvable even without a webserver, but it would be more elegant with a webserver.Lajos Arpad

2 Answers

1
votes

Per page set a variable on either the window object or declare it in the global scope with var. This will allow the set value to be accessible to other scripts as they are now global.

Change the value of this property or variable on every page to get the data connected to the page.

<html>
  <head>
    <title>Page</title>
  </head>
  <body>
    <script>
      window.__api__ = 'https://goodman456.000webhostapp.com/api.php';
    </script>
    <script src="script.js"></script>
  </body>
</html>

Then in the API script use this global value as the endpoint to use with fetch.

const retrieveAllQuotes = async function() {
  const response = await fetch(window.__api__);  
  const data = await response.json();
  return data;
}

The __ namespacing is to ensure that the variable name has very little chance to be overwritten by future browser updates.

0
votes

I doesn't have enough "reputation" to comment but I am giving you an idea that make that such as for checking URL using if conditions For example.

if((window.location.herf).indexOf("lo.html") > -1 ){
//To your love API
const response = await fetch('https://goodman456.000webhostapp.com/api.php');
}
else if((window.location.herf).indexOf("hp.html") > -1 ){
//To your desired API and so on

const response = await fetch('https://goodman456.000webhostapp.com/api.php');

}

Thanks.