How to randomize .class names inside .hasClass() in jQuery

Viewed 125

I have a code of this:

$(".user-items").each(function() {
  if ($(this).hasClass("don't know the code yet")) {
    $(this).fadeIn();
  } else {
    $(this).fadeOut();
  }
});

but I wanted it to work like this:

$(".user-items").each(function() {
  if ($(this).hasClass(".people OR .photos OR .videos")) {
    $(this).fadeIn();
  } else {
    $(this).fadeOut();
  }
});

I wanted to randomize the 3 classes in every .each() loop and make all matched elements fadeIn/fadeOut

Note*: The "OR" inside .hasClass is just an interpretation of how I wanted it to work

<a href="javascript:void(0);" class="user-items people">People</a>

<a href="javascript:void(0);" class="user-items photos">Photo</a>

<a href="javascript:void(0);" class="user-items videos">Videos</a>
...
...
...
lots of more .user-items classes with 3 given classes: .people, .photos, .videos

Thank you

1 Answers

You could use an array of classes then random() method to get every time a random class like :

var classes = ['photos', 'videos', 'people'];

$(".user-items").each(function() {
  var random_class = classes[Math.floor((Math.random() * classes.length) + 0)];

  console.log(random_class);

  if ($(this).hasClass(random_class)) {
    $(this).fadeIn();
  } else {
    $(this).fadeOut();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="javascript:void(0);" class="user-items people">People</a>
<br>
<a href="javascript:void(0);" class="user-items photos">Photo</a>
<br>
<a href="javascript:void(0);" class="user-items videos">Videos</a>

Related