Convert Jquery to Javascript

Asked

Viewed 127 times

0

Good afternoon,

I would like to convert this code below to Javascript:

                $('.circles > div').click(function () {
                    let index = $('.circles > div').index(this);
                    $('.circles > div').removeClass('active');
                    $(this).addClass('active');
                    $('.steps-carousel').css('transform', 'translateX(' + (index * -20) + '%)');
                });

Someone could help me?

  • Have you tried anything? Do you understand this jQuery code and what it does? What lines don’t you understand?

  • This code was a Steps I created with a Carousel, but I created it in Jquery and where I will deploy does not use Jquery.

  • What it does: When I click on the circle, it removes the active class and adds in the circle I clicked and changes the Carousel item. Only it doesn’t work because in the system that I’m going to deploy, it doesn’t have Jquery, so it has to be pure javascript

  • You know for example what $('.circles > div').index(this); ago?

  • Come on: , within the "Circles" class, has Ivs with no class or id, just div. , this "$('.Circles > div'). index(this);" stores within the index variable (Let index) the div I clicked on.

2 answers

0

Here is a hint, not tested but with reference to which line of code it matches. I’m not sure if in your HTML carousel is just one element or several... but corrects if it is not.

const carousel = document.querySelectorAll('.steps-carousel');
const divs = document.querySelectorAll('.circles > div');

divs.forEach((div, index) => {
  // aqui o index é o mesmo que let index = $('.circles > div').index(this);
  div.addEventListener('click', () => { // $('.circles > div').click(function() {
    div.forEach(el => el.classList.remove('active')); // $('.circles > div').removeClass('active');
    div.classList.add('active'); // $(this).addClass('active');
    carousel.forEach(el => el.style.transform = 'translateX(' + (index * -20) + '%)'); //$('.steps-carousel').css('transform', 'translateX(' + (index * -20) + '%)');
  });
});

0

Document.querySelectorAll to use queries like Javascript. To assign classes/attributes to each element you have to iterate over each of them, using foreach for example. So just use the native Javascript methods to do what you need.

const circleDivs = [...document.querySelectorAll('.circles > div')];
const stepsCarousel = [...document.getElementsByClassName('steps-carousel')];

circleDivs.forEach(el => el.addEventListener('click', (e) => {
  const index = circleDivs.indexOf(el);

  circleDivs.forEach(el => el.classList.remove('active'));
  el.classList.add('active');
  stepsCarousel.forEach(el => el.style.transform = 'translateX(' + (index * -20) + '%)');

}));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.