javascript - Select divs with the same attribute from an Jquery object -
i have grid of 6 divs attribute row
nested equally between 2 divs attribute col
. when page loads want randomly select 1 of rows , apply class .show
, both divs row="1"
1 row
. here, when document clicked want 1 of rows out of remaining 2 rows randomly selected , have class .show
applied it. when document clicked again, last remaining row
showed have .show
applied it. 3 row
s have class .show
. if document clicked again visual cycle should restart 1 randomly selected div
has class .show
.
i have created jsfiddle code far. can't work out how select divs same row
attribute.
<div id="cnt"> <div col=0> <div row="0">0</div> <div row="1">1</div> <div row="2">2</div> </div> <div col=1> <div row="0">0</div> <div row="1">1</div> <div row="2">2</div> </div> </div>
js
$(document).ready(function() { function selectdiv(){ var notselecteddivs = $("div[row]:not(.show)"); if(!notselecteddivs.length){ $('.show').removeclass('show'); notselecteddivs = $("div[row]:not(.show)"); } var randomindex = math.floor((math.random() * 3)); $(notselecteddivs).attr('row', randomindex).addclass('show'); } $(document).on("click", function() { selectdiv(); }); selectdiv(); });
the divs rows can found using jquery selector [row=value]
. random index: $('div[row=' + randomindex + ']')
quick example (upper bound rows hard coded example): fiddle
edit example implementation:
$(document).ready(function() { let rowdivs = $('div[row]'); function selectdiv(){ let notselecteddivs = rowdivs.not('.show'); if(!notselecteddivs.length) notselecteddivs = rowdivs.removeclass('show'); var randomindex = notselecteddivs.get(math.floor((math.random() * notselecteddivs.length))).getattribute('row'); $('div[row=' + randomindex + ']').addclass('show'); } $(document).on("click", function() { selectdiv(); }); selectdiv(); });
#cnt { display: flex; } div[row] { width: 20px; border: 1px solid black; } .show { background-color: yellow; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="cnt"> <div col=0> <div row="0">0</div> <div row="1">1</div> <div row="2">2</div> </div> <div col=1> <div row="0">0</div> <div row="1">1</div> <div row="2">2</div> </div> </div>
Comments
Post a Comment