Accounting for DOM changes in js widget


#1

I have an SPA in Codepen (https://codepen.io/bsands/pen/BZMOgd) where I have a quote that is changed every time I press a button. Once I have a quote I like, I’d like to Tweet out that quote. The Twitter js widget allows me to tweet out whatever the very first quote was, but none of the subsequent quotes, even though I’m updating the data-text attribute in the <a>. Actually, the update works perfectly on the initialization of the page. It just won’t allow for subsequent updates, likely due to the single scan from the js widget.

How do I get the widget to re-scan the page to see the changes?
Or, how do I get the widget to re-scan the page on each button click? The twttr.widgets.load() doesn’t work in the changeQuote function.

Thanks. JS below.

var quoteArr = [
  {
    num: 1,
    quote:
      "You must be out of your mind, son! You can't cut the cheese, where ever you please! That's just nasty!"
  },
  { num: 2, quote: "Break was over 15 minutes ago, Mitch!" },
  {
    num: 3,
    quote:
      "That ain't your cake, Phillip, that's Simone's cake. You eat someone else's cake again, and I will get you a slice of Terry's very special pain cake. And you won't want seconds o' that."
  },
  { num: 4, quote: "You kill the joe, you make some mo'! You know that baby!" },
  {
    num: 5,
    quote:
      "Whooo! You can't walk away from a K-22 paper jam! You must be out of your mind, son! This is my world, Donnie, you just work here baby!"
  },
  {
    num: 6,
    quote: "This ain't your home, so don't use the speakerphone, Roger! Whooo!"
  }
];

function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min)) + min;
}

var first = getRandomInt(0, 6);

document.addEventListener("DOMContentLoaded", function() {
  document.getElementById("thequote").innerHTML = quoteArr[first]["quote"];
  document.querySelector("#share").setAttribute("data-text",quoteArr[first]['quote']);
});

var last = first;
var next = getRandomInt(0, 6);
function replaceQuote() {
  last = next;
  document.getElementById("thequote").innerHTML = quoteArr[last]["quote"];
  while (next === last) {
   next = getRandomInt(0, 6); 
  }
  document.querySelector("#share").setAttribute("data-text",quoteArr[last]['quote']);
}

window.twttr = (function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0],
    t = window.twttr || {};
  if (d.getElementById(id)) return t;
  js = d.createElement(s);
  js.id = id;
  js.src = "https://platform.twitter.com/widgets.js";
  fjs.parentNode.insertBefore(js, fjs);

  t._e = [];
  t.ready = function(f) {
    t._e.push(f);
  };

  return t;
}(document, "script", "twitter-wjs"));

#2

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.