Transform a dropdown menu into a list based on the size of the screen

I'm working with an HTML select tag

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

My goal is to present the different options as a horizontal list of <a> hyperlinks on larger screens (above 481px) and as a dropdown list for smaller screens (480px and below). When one of the hyperlinks is clicked, it should reflect the same option values as in the original select tag.

I've come across examples online where a list of <a> elements was transformed into what appeared to be a dropdown list using jQuery. However, upon closer inspection, it seemed that these elements were simply stacked on top of each other and displayed as a dropdown when clicked.

Answer №1

There are 3 simple steps to follow:

1) Utilize jQuery to replicate a select dropdown as an unordered list of links,

2) Apply media queries to switch between displaying the list and the dropdown,

3) Use jQuery to ensure that active selections are synchronized between both elements; for example, if the second dropdown option is chosen, the second link will also be marked as active, and vice 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 selection and synchronize

// 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 content is static and unlikely to change, you can eliminate the JavaScript associated with step 1 and manually create the ul link list in your HTML code.

Check out this jsFiddle example for a visual representation.

Answer №2

There are multiple ways to achieve this objective.

1) Utilize @media queries to display/hide various elements that serve the same purpose.

You can have a select and a ul that switch visibility based on the viewport width. Check out this Example - resize fiddle output window

2) Implement jQuery

Use JavaScript to dynamically convert the options in the select into a ul. Here's an Example - credit goes to this thread

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transforming the iOS link background color as you scroll

My website features a collection of products displayed within clickable a links styled with display:block for full clickability. However, I've encountered an issue where the background color of the a link changes to an active state color when scrollin ...

Is there a way to include a textarea or text input in a table row and have it expand upon clicking or dragging, without increasing the row height?

I am looking for a way to allow a textarea to expand or grow when clicked or dragged, without affecting the height of the table row it is in. You can see an example of the issue on this CodePen: https://codepen.io/kerastensorflow/pen/PobaRvK?editors=1010 ...

Is there a way to define the class for a <dt> element within a Zend_Form configuration?

Is it possible to set a specific width for a group of < dt > elements within a Zend_Form by applying a class? I need the end result to look like this: <dt id="name-label" class="xyz" > <label class="required" for="name">Name ...

Vanilla JavaScript - Conceal all remaining div elements

I have a situation where multiple divs are only visible after clicking a link. How can I ensure that when one div is clicked, all others are closed so that only the clicked one remains visible? Currently, I am using the following JavaScript: functio ...

Transforming functions with dependencies into asynchronous operations with the help of promises

Can I convert both of my functions into asynchronous functions, even though one function relies on the other? Is it feasible for function b to execute only after function a? ...

Tips for aligning Jqplot Bar Chart point labels vertically

Struggling to create a graph and seeking assistance after numerous failed attempts. My code is shared below: var plot2 = $.jqplot('distance_graph', data.distance, { // The "seriesDefaults" option is an options object that will ...

How can a material progress spinner be inserted into the Angular Ag-Grid overlayNoRowsTemplate?

I'm attempting to include a mat-progress-spinner within my agGrid when there are no rows to display. Here's an example that works: private overlayNoRowsTemplate = '<p>No rows to show.</p>'; However, when I attempt to add ...

Ways to modify the color of a particular list item

I am looking to change the color of only the items in a list that contain a number to blue. Specifically, I want to target the first list (the ol li) that starts with a number in it. ol li { color: blue; } <ol> <li>League 1<br> ...

Customizing label printing using HTML and CSS. Learn how to dynamically adjust label and container sizes based on label dimensions

After spending some time developing the code for a label size of 5cm by 2.2cm, I have successfully printed it without any issues. Now, my goal is to create a flexible solution that automatically adjusts font sizes and containers for various label sizes. T ...

Having trouble aligning the links to the correct heights on my website due to the interference of the menu

I recently designed a website with a fixed menu where the links scroll down the page to the corresponding content section when clicked. However, I encountered an issue where the fixed menu blocks part of the content after scrolling. I wish the content wo ...

When using Stacked area in Highcharts, my data series gracefully transition between visibility and opacity

Here's a question I have regarding a stacked area graph visualization. Take a look at this image: https://i.sstatic.net/Rk9tg.png What I'm aiming for is to have "test1" end directly at 2024, instead of gradually fading out towards 2028. Similar ...

Using jQuery to modify CSS attributes is proving to be more challenging than I anticipated

I am attempting to modify a CSS attribute using jQuery. I have used the following code: wrapperInner.css('overflow', 'visible'); However, the value remains unchanged. When I use an alert alert(wrapperInner.css('overflow')), ...

jQuery setup for doWhen

Struggling to get doWhen functionality to work properly. Here is my index.html setup: <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <script type="text/javascript" src="js/jquery.dowhen.min.js"></sc ...

Using JQuery and AJAX to add content to a specialized text log file

I want to enhance a custom log file with date information to monitor clicks on a specific link, but all contents in the TXT file are being overwritten: $('#cal').click(function() { $.ajax ({ url: 'caltrack.php', da ...

Updating a conditional statement in jQuery

Understanding jQuery has always been a challenge for me. I find myself spending hours reading documentation every time I try to implement it, only to achieve very little progress. Here's the code I'm currently working on with live-editing availab ...

Changes made to the main.css file were erased when running gulp install within the JHipser project

Just diving into the world of jhipster. I recently included a new css property in the main.css file and referenced it in the home.html. However, after executing the gulp install command, that modification vanished from the main.css. Is there a way to ret ...

Lightgallery experiencing technical difficulties

Encountering difficulties while trying to integrate lightgallery into my website. Despite searching on stack overflow and reading the documentation on the lightgallery page, I am unable to identify the issue! Below is the code snippet from my site: <!d ...

Incorporate the "0" character into a PHP JSON call

I am currently working on a PHP page to retrieve data from Forecast.io's API. When looking at the daily view, they represent the days as numbers. I specifically need information for today, which is represented by the number "0." Here is an excerpt of ...

What causes the size of an image to decrease when placed within an anchor tag?

Trying to add clickable social media icons, but when wrapped in an anchor tag the images shrink significantly. <span class="iconspan"> <a href="https://www.instagram.com/lil_ijoez/" target="_blank" ...

How can I create an image that spans the entire width of the screen, Swiper?

var swiper = new Swiper('.swiper-container', { pagination: { el: '.swiper-pagination', }, }); html, body { position: relative; height: 100%; } body { background: #eee; font-fami ...