Home > Software engineering >  Converting simple text fade loop from jQuery to Javascript
Converting simple text fade loop from jQuery to Javascript

Time:01-05

I have three divs with text inside them which I want to fade in and out on a loop. I had it working in jQuery but decided its best to be in pure Javascript:

<div >
  <h2 >first quote</h2>
  <h2 >second quote</h2>
  <h2 >3rd quote</h2>
</div>

I am trying to convert this jquery into pure vanilla Javascript:


  var quotes = $(".quotes");
  var quoteIndex = -1;

  function showNextQuote() {
      quoteIndex;
    quotes.eq(quoteIndex % quotes.length)
      .fadeIn(2000)
      .delay(2000)
      .fadeOut(2000, showNextQuote);
  }

  showNextQuote();

})();

So far I have manage to convert it to this in pure javascript:


  let quotes = document.getElementsByClassName("quotes");
  let quoteIndex = -1;

  function showNextQuote() {
      quoteIndex;
    quotes.eq(quoteIndex % quotes.length)
      .fadeIn(2000)
      .delay(2000)
      .fadeOut(2000, showNextQuote);
  }

  showNextQuote();

})();

I am seeing an error of quotes.eq is not a function and am unsure how to fix this.

Any suggestions much appreciated.

Thanks

CodePudding user response:

document.getElementsByClassName returns an HTML collection so it's like an array you can access with an index.

The elements in a collection can be accessed by index (starts at 0).

Try this

quotes[quoteIndex % quotes.length]

CodePudding user response:

eq, fadeIn and fadeOut functions are not vanilla JS functions. You can write the code like this for eq function.

document.querySelectorAll('.quotes')[quoteIndex % quotes.length].textContent = 1254;

And you should write the code in Vanilla JS for fadeIn and fadeOut. Please referent this link

CodePudding user response:

In your code quotes is an HTMLCollection, which doesn't have a .eq() method like the jQuery. Instead, you can use the modulo operator (%) to loop through the quotes collection and access each element using the quoteIndex variable.

let quotes = document.getElementsByClassName("quotes");
let quoteIndex = -1;

function showNextQuote() {
    quoteIndex;
  let currentQuote = quotes[quoteIndex % quotes.length];
  currentQuote.style.display = 'block';
  setTimeout(function() {
    currentQuote.style.display = 'none';
    showNextQuote();
  }, 4000);
}

showNextQuote();
  • Related