user3720751 user3720751 - 6 months ago 9
HTML Question

Displaying a custom attribute of a div with jquery and css

I'm a hobby coder and have a query that I just cant seem to find an answer for. I would think that it would be quite simple, but perhaps I'm not searching the correct syntax... hopefully you can help me.

I have a series of

<div>
s on a page with a number of custom attributes. Here is the example:

<div class="face" rownumber="1" rowposition="0" playername="Jo Smith" playerrole="Captain"
playerposition="0" style="position: absolute; left: 772.632px; top: 215.934px;
width: 46.5668px; height: 46.5789px; color: rgb(255, 255, 255);
background-color: rgb(255, 0, 0);"></div>


How in css, can I have all the
<div>
s with the class of 'face' display the "rownumber".... and then after clicking on a button, they all display "playername".... and then after clicking on a different button, they all display "playerrole"

Thankyou for reading and hopefully answering....

Answer

Yes. This works by changing the class on the 'selected' element, and using CSS to render the different values based on what class it is.

$('.selector').click(function(){
  $('#selected').attr('class',$(this).text());
});
.rownumber .face:after { content: attr(rownumber); }
.playername .face:after { content: attr(playername); }
.playerrole .face:after { content: attr(playerrole); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='selected' class='rownumber'>
<div class="face" rownumber="1" rowposition="0" playername="Jo Smith" playerrole="Captain" 
     playerposition="0" style="position: absolute; left: 772.632px; top: 215.934px; 
     width: 46.5668px; height: 46.5789px; color: rgb(255, 255, 255);
     background-color: rgb(255, 0, 0);"></div>
 </div>
<button class='selector'>rownumber</button>
<button class='selector'>playername</button>
<button class='selector'>playerrole</button>

If you want an all css solution, you can do this:

[name=selected][value=rownumber]:checked ~ div .face:after {
  content: attr(rownumber);
}
[name=selected][value=playername]:checked ~ div .face:after {
  content: attr(playername);
}
[name=selected][value=playerrole]:checked ~ div .face:after {
  content: attr(playerrole);
}
<input type='radio' name='selected' value='rownumber'>Rownumber
<input type='radio' name='selected' value='playername'>Playername
<input type='radio' name='selected' value='playerrole'>Playerrole
<div>
  <div class="face" rownumber="1" rowposition="0" playername="Jo Smith" playerrole="Captain" playerposition="0" style="position: absolute; left: 772.632px; top: 215.934px; 
     width: 46.5668px; height: 46.5789px; color: rgb(255, 255, 255);
     background-color: rgb(255, 0, 0);"></div>
</div>

Comments