javascript - Getting a elements position in a grid divided by 4 -
i have grid of let's 12 cards, 4 columns , 3 rows. every column has different class. column 1: has class a. column 2: has class b , on c , d.
if loop through cards class of a, can know row position because jquery's each has index.
my problem when clicks card let's column b row 2 how can index then, know it's in column 2 because has class of b, how know row is?
what need math function can pass in let's 7 (if 7th card pressed) , return 2 (because it's in second row) , , 10 return 3.
i used example 12 cards math function should return amount of cards.
so lets assume cards have class .card if not should add 1 here's you'd , can either jquery or javascript
//now first want create variable of how many cards per row //in example set manually 4. var cardsinrow = 4; //function calculates row position function getcardrow () { //this card clicked on //to use if jquery enabled var index = $('.card').index(this); //to use if want vanilla, , use javascript array function //bind .card query use //now return index of card in query if array. var index = [].indexof.call(document.getelementsbyclassname('card'), this); //now add 1 index since it's 0 based , return row number alert( math.ceil( ++index / 4 ) ); } //you can use javascript click event $('.card').on('click', getcardrow); //or use javascript var = 0, cards = document.getelementsbyclassname('card'), len = cards.length; (i = 0; i<len; i++) { cards[i].onclick = getcardrow }
Comments
Post a Comment