Get random quotes using Vanilla.JS

I have kicked off my Free Code Came 30 days of projects with the first intermediate front end project Build a Random Quote MachineIncomplete, and I thought it would be easy…

I thought, If it’s gunna be easy why not self impose rules to make it more challenging right? Why use jQuery or another frame work when we can write it from scratch with Vanilla JS? Man I really seem to love learning the hard way …….. <.<

Example project they provide

The deliverables of the project:

  • Be able to click a button to load a new quote.
  • Be able to click a button to tweet out the quote (auto fill tweet text with quote)

Problems, Fixes, and what I learned:

Problem: Ajax requests via “new XMLHttpRequest()” aren’t really a thing anymore because of security reasons. We kindly get this error “Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.” Maybe it’s just chrome idk, didn’t look that far into it.

Solution: Make requests with script tags. To do so just make a script tag, set it’s src attribute to the url you want then append that script in the body or head tag. After that the request gets made and the data gets loaded. Chrome also wants https, not http.

Problem: Needing to access the returned data.

Solution: To access the data you need to have the server return it wrapped in a callback. The callback has to be visible in the global scope and the callback has to have a unique name. When the global callback function gets called, remove it and pass along your data.

Problem: Needing to have the tweet buttons text automatically filled by dynamically changing quote text.

Solution: You can auto fill the tweets text by creating an a tag, and setting it’s href attribute to “” plus the string you want to be auto filled in at the end. But apparently twitters widget api will turn your a tag element into an iframe? so could no longer just reach out and change the a tag’s href attribute when I got a new quote, Even when I kept a reference to it. So now it just destroys the button and creates a new one each time the quote changes. Not the most elegant but it works.

My quote generator

My source code

My take aways:

  • Don’t under estimate a project’s difficulty when you have not implemented something similar.
  • Use available abstractions first if easier, then go back and reimplement from scratch for learning purposes.