2

I'm trying to transform this little piece of code:

$(document).ready(function () {
    $('.slider').slider();
});

to pure JavaScript code. I've followed some links and I've tried to rewrite the code above in two ways:

first option:

var slider2 = document.querySelectorAll(".slider");

window.onload = slider2.slider;

second option:

var slider2 = document.querySelectorAll(".slider");

document.addEventListener("DOMContentLoaded", function() {
    slider2.slider();
});

In both cases I get no errors, but it doesn't show anything...

Any other ideas? :(

UPDATE: Ok, for some reason, the option with the DOM Events didn't work for me...

This is the code that I came up with that solved my problem:

var elems = document.querySelectorAll('.slider');

var instances = M.Slider.init(elems, {
    inDuration : 275
});

window.addEventListener("load", instances, false);

Initially I used just window.onload = instances, but I was using the same logic in another JS file, so I ended up overriding the other event. In the solution above, I got rid of that problem.

user3063909
  • 363
  • 3
  • 16

4 Answers4

2

So $('.slider').slider() is not the same as document.querySelectorAll(".slider"). The former (using $) applies any jQuery plugins that exist, eg Materialize CSS's as you've mentioned you're using. The latter (document.querySelectorAll) does not as this is a native browser function.

So if you really want to use vanilla, you need to look at Is it possible to use Materializecss without jQuery?

Ahmed Nuaman
  • 12,662
  • 15
  • 55
  • 87
0

The method "querySelectorAll" returns a list (more precisely, a NodeList), so neither of those would do what you want.

Try the following ("DOMContentLoaded" is, i think the type of event you want):

document.addEventListener("DOMContentLoaded", () => {
  document.querySelector(".slider").slider();
});

Hope this helps!

Harbinger
  • 26
  • 2
0

From the Materializecss documentation:

  document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('.slider');
    var instances = M.Slider.init(elems, options);
  });

You can't use .slider() because that is meant to be called on a jquery instance since it is a jquery plugin.

Nathan
  • 11,814
  • 11
  • 50
  • 93
0

On this website slider can initiate in Javascript

document.addEventListener('DOMContentLoaded', function() {
        var elems = document.querySelectorAll('.slider');
        var instances = M.Slider.init(elems, options);
      });

And it is the same with jQuery:

  $(document).ready(function(){
    $('.slider').slider();
  });
little_coder
  • 564
  • 3
  • 13