Search code examples
javascriptcssformsradio-buttonfallback

Show div on radio button check using JS fallback


I am building a website of which the desktop version displays 10 images all at once (5x2), which obviously doesn't look too good on a small smartphone display. In order to conquer this problem, I made 10 radio buttons (which only display on the mobile version of the website) and only show the image that accompanies the checked radio button. This was very easy to implement with HTML and CSS3 like this:

HTML:

<input type="radio" name='pdr' id="pdr1"><label for="pdr1"> Click here</label>
<div class="populardevice" id="populardevice1">stuff in this div</div>

CSS:

.populardevice {
  display: none;
}
input#pdr1:checked ~ #populardevice1 {
  display: inline;
}

The problem is that older browsers don't support the :checked selector. My idea was to use the CSS3 way of displaying the div if it's supported, and use JavaScript as a fallback if not. I already found this, which is basically what I want. The only problem is how do I detect if support for the :checked selector is present? I was thinking of Modernizr but it seems like all that would do is create an additional class in my CSS that says no-checked (right?), which would be of no use to me since I want to run a piecie of JS in that case. Or would Modernizr be fit for this case, utilizing it something like this (pseudo-code - I have no idea how to write this yet but if it's the solution, I will find out how):

if (Modernizr.:checked supported) {
  use that and terminate this function;
} else {
  Execute the JavaScript function from the link above;
}

Or do you guys advise me to implement something completely different?

Thanks in advance.


Solution

  • From the Modernizr website:

    Using Modernizr with JavaScript

    The Modernizr object

    Modernizr keeps track of the results of all of it's feature detections via the Modernizr object. That means that for each test, a corresponding property will be added. You just have to test for truthiness in your code to figure out what you want to do

    if (Modernizr.awesomeNewFeature) {
      showOffAwesomeNewFeature();
    } else {
      getTheOldLameExperience();
    }
    

    So your pseudo code was pretty close!