1

I have an HTML select tag

<select class="filter">
   <option values="1">One</option>
   <option values="2">Two</option>
   <option values="3">Three</option>
</select>

I would like to display the different options as an horizontal list of <a> hyperlinks for screen sizes above 481px and assign the same option values as in the select tag when the hyperlinks are clicked/selected and as a dropdown list for screen sizes of 480px and bellow.

I have seen examples online where a list of several <a> elements would be transformed into what looks like a dropdown list using jquery, but what it really did was taking all of these elements and stacking them over eachother and display the dropdown when clicked.

LaGuille
  • 1,518
  • 5
  • 18
  • 37

2 Answers2

3

3 steps involved;

1) use jQuery to duplicate select dropdown into unordered list of links,

2) use media queries to toggle between displaying the list and the dropdown,

3) use jQuery to sync active selections between both, ie, if the second dropdown option is selected, it sets the second link as active as well, and visa versa.

$('select.filter').after('<ul class="list"></ul>');
$('select.filter option').each(function () {
    $('ul.list').append('<li><a href="#" data-value="' + $(this).val() + '">' + $(this).text() + '</a></li>');
});

//set first item as active on ready
$('ul.list li:eq(0)').addClass('active');

// set active to selction and sync

// update dropdown when links selected
$('ul.list > li > a').click(function(){
   $('ul.list > li').removeClass('active');
   $(this).parent().addClass('active');
    var e =  $(this).parent().index();
   $('select.filter option:eq('+e+')').prop('selected', true);
});
// update list when dropdown selected
$('select.filter').change(function() {
    var e =  $('option:selected', this).index();
    $('ul.list > li').removeClass('active');
    $('ul.list > li:eq('+e+')').addClass('active');
});

Note: If your html is static and you know it is not going to change, or is very unlikely to change, you can remove all of the JavaScript associated with step 1 and manually create the ul link list in your html.

jsFiddle working example

partypete25
  • 4,253
  • 1
  • 15
  • 16
0

There are a couple of ways to accomplish this.

1) Use @media rules to show/hide different element that perform the same function.

You can have a select and a ul that show/hide depending on viewport width. See Example - resize fiddle output window

2) Use jQuery

Use javascript to simply take the options in the select and transform it into a ul - See Example - all credit to this question

Community
  • 1
  • 1
justinw
  • 3,586
  • 5
  • 25
  • 40