1

I am working on api to generate random quotes. its working fine but i want to generate a random quotes as soon as page load.

document.getElementById('load').addEventListener('onload', loadData);
document.getElementById('getQuote').addEventListener('click', loadData);

    function loadData() {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', 'https://talaikis.com/api/quotes/', true);
        xhr.onload = function() {
            if (this.status === 200) {
                const data = JSON.parse(this.responseText);
                document.getElementById('quote-message').innerHTML = `<h1>${data[0].quote}</h1>`;
                document.getElementById('author').innerHTML = `<h3>${data[0].author}</h3>`;
            }
        }
        xhr.send();
    }
Narendra Jadhav
  • 10,052
  • 15
  • 33
  • 44
Amrendra Nath
  • 74
  • 1
  • 11

2 Answers2

-1

As per JavaScript that executes after page load

Use window.onload to launch a script on document load:

window.onload = loadData;

Your full code will then look like

window.onload = loadData;
document.getElementById('getQuote').addEventListener('click', loadData);

function loadData() {
 // [...]
}
klugjo
  • 19,422
  • 8
  • 57
  • 75
  • Thanks. it worked. but i have some queries. why my addeventlistener was not working? – Amrendra Nath Apr 02 '18 at 05:48
  • because the `onload` event does not happen to the `id=load` element, but to the `window` element. So you would have to use `window.addEventListener('load', loadData);` (note that the syntax is `load` and not `onload`) – klugjo Apr 02 '18 at 05:50
-2

i guess your question is, why the function is not working when the page loads, try enclosing your function loadData in $(document).ready(). A function enclosed in $(document).ready()will execute when the page is done loading.

edit: correction not load, ready thanks.

whitespace
  • 789
  • 6
  • 13