Skip to content Skip to sidebar Skip to footer

Select 2 Random Divs With The Same Class Jquery

my question is simple, suppose I have 10 divs:

Solution 1:

Try this - Use Math.Random and parseInt

Working Demo Here

$(document).ready(function(){
    var r1 = (Math.random()*10);
    var r2 = (Math.random()*10); 
    if(parseInt(r1)==parseInt(r2)) // IF BOTH ARE SAME
    {
       if(parseInt(r1)==10)
       {
           r2=r2-1;
       }
       else
       {
          r2=r2+1;
       }
    }   
    var allDiv = $('.someDiv');    
    $(allDiv[parseInt(r1)]).css({'background':'red'});
    $(allDiv[parseInt(r2)]).css({'background':'red'});
});

Solution 2:

Here is the simplified version of https://stackoverflow.com/a/11186765/2000051

Demo: http://jsfiddle.net/lotusgodkk/fK8Xw/69/

JS:

functionshuffle(array) {
    var m = array.length,
        t, i;
    while (m) {
        i = Math.floor(Math.random() * m--);
        t = array[m];
        array[m] = array[i];
        array[i] = t;
    }
    returnarray;
}

$(function () {
    $("button").click(function () {
        var$all = $(".someDiv").removeClass("red");
        $(shuffle($all).slice(0, 3)).addClass("red");
    });
});

Solution 3:

A generalized approach for specified number of elements to change. just change var numOfDivToChange=2; to apply the effect to more elements.

$(document).ready(function(){
    var numOfDivToChange=2;
    $('.foo').click(function(){


        //get all similar elements arrayvar allFoos = document.getElementsByClassName('someDiv');

        //sanity checkif(numOfDivToChange>allFoos)
             returnfalse;

        for(var i=0;i<numOfDivToChange;i++)
        { 
           //generate a random indexvar   randIndex = Math.floor((Math.random() * allFoos.length) + 1);

           //set the css changes you want
           allFoos[randIndex].css('background','red');
        }
    });
});

Solution 4:

Try This

UPDATE:

$(document).ready(function(){
    $('.foo').click(function(){
        var rand1 = Math.floor((Math.random() * 10) + 1);
        var rand2 = Math.floor((Math.random() * 10) + 1);
        var a = document.getElementsByClassName('someDiv')[rand1];
        var b = document.getElementsByClassName('someDiv')[rand2];
        a.css('background','red');
        b.css('background','red');
    });
});

Post a Comment for "Select 2 Random Divs With The Same Class Jquery"