Alexey Ayzin Alexey Ayzin - 1 year ago 78
CSS Question

Modifying CSS Using Select Tag

I have a list of options:

<select id="numOfcards">
<option value="Select">Select</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>

I also have flip-container that is, as a default, set at 33% width:

.flip-container {
perspective: 1000px;
display: inline-block;
width: 33%;
min-width: 400px;
padding-right: 2px;

What I want to ultimately happen is this:

When the option 1 is selected, the width is 100%.
When the option 2 is selected, the width is 48%.
When the option 3 is selected, the width is 33%.
When the option 4 is selected, the width is 24%.
When the option 5 is selected, the width is 19%.

I don't need the full code for this, just to know if (A) this is possible without a backend language, and (B) the main concept behind it. I looked through google and stackoverflow and couldn't seem to find a question with these exact specifications. Preferably, I would want the answer as JS.


Answer Source

Good question. There are no practical ways to do this with pure-CSS, but it can be done quite easily with JavaScript. Each option should have data of the target width: i.e.
<option value="1" data-width="100%">1</option>

Then at the end of your page, add a <script>. Usually scripts are stored in separate .js files, so you add <script src="main.js"></script>. <script> src works just like <img> src, but you can also do inline scripts if you prefer not to store them in a separate file.

main.js will look like

var select = document.getElementById('numOfcards')
var containers = document.querySelectorAll('.flip-container')
select.onchange = function () {
  var selectedOption = this.options[this.selectedIndex]
  for(var i = 0; i < containers.length; i++)
    containers[i].style.width = selectedOption.getAttribute('data-width')