0

I have the following function:

$(".schedule").each(function () {
    var cls = this.className.match(/schedule-\d+/);
    if (cls.length === 0) return;

    var els = $(".schedule." + cls); 
    if (els.not(this).length > 0) {
        els.addClass("someClass");        
    }
});

It adds a class (.someClass ) to divs that have the same class, turning the div red. As seen in this fiddle, it works. I'd like to add this someClass class randomly to max 2 divs with the same class.

Example (ps: The order of the div classes are generated randomly and they are not limited to just A,B,C and D. This order and class names in the fiddle are just an example):

We have A, B, C, A, C, D, A.

I want randomly 2 divs with the same class turn red so:

  1. A and (second) A is red OR
  2. A and (third) A is red OR
  3. (second) A and (third) A is red OR
  4. C and C is red

If this is very complicated I'll settle for the first found match too. So:

  1. A and (second) A is red

Hope someone can help, thanks!

Maurice
  • 1,147
  • 2
  • 21
  • 49

1 Answers1

1

A and (second) A can be selected using:

$('.a:eq(0), .a:eq(1)').addClass('someClass');

A and (third) A would be:

$('.a:eq(0), .a:eq(2)').addClass('someClass');

Similarly, you can get the other combinations as well. This is assuming the total number of combos is what you've specified in the question.


Ok, to select 2 random elements of a given class to operate on, you can do:

// total number of elements with class (.A, .B, .C etc.)
var n = $('.yourClass').length;

// get 2 indices randomly
var ids = [];
while(ids.length < 2) {
   var r = Math.floor(Math.random() * n);
   if(ids.indexOf(r) == -1) {
      ids.push(r);
   }
}

// select the 2 elements picked randomly
var sel = $('.yourClass:eq('+ids[0]+'), .yourClass:eq('+ids[1]+')');

// apply the class
sel.addClass('someClass');
techfoobar
  • 65,616
  • 14
  • 114
  • 135
  • _I'd like to add this someClass class **randomly** to max 2 divs_ – Andreas Apr 22 '13 at 19:23
  • Indeed OR to the first found match. Also the classes are not fixed (nor in order nor in names). Nevertheless thanks for trying to help! – Maurice Apr 23 '13 at 06:09
  • @Maurice - See my edit. Have added some logic to help you get what you need. – techfoobar Apr 23 '13 at 06:30
  • @techfoobar thanks techfoobar but when I try implementing this in my Fiddle (see main post), it crashes the site :( Also I understand I need to replace `.yourClass` with a class from the script. This is not workable (unless all used classes are loaded automatically) for me since many different classes are loaded in the original script (It can be A, B, C, etc but also B, D, E, etc). Any other ideas? Thanks again for the effort (think I should go for the first found match. Think it's easier to accomplish) – Maurice Apr 27 '13 at 19:14