Designing a dropdown menu that alters the size based on the selected item

Consider a scenario like amazon.com, where clicking on the filter in their search bar changes the size of the selected item while the other items remain at a fixed size.

Now, suppose I have the following HTML

<select>
    <option value="book">book</option>
    <option value="board_game">board game</option>
    <option value="dvd">DVD</option>
    <option value="all">All</option>
</select>

If I want to make the selected item, such as 'all', have a smaller width than when 'board_game' is selected. How can I achieve this using CSS and possibly jQuery?

Answer №1

It appears that styling select options can be quite limited. My suspicion is that Amazon has deviated from the standard select-option markup and is possibly using JavaScript to present a div in place of the option menu. This approach allows them to achieve the desired effect you're aiming for.

While I may not know the exact effect you're seeking, I've prepared a codepen that could serve as a helpful foundation for your project. This code utilizes jQuery to populate a hidden container that becomes visible when interacting with a dummy select menu.

The basic HTML structure is as follows:

<div id="select">
    Item Select
    <option value="book" disabled>book</option>
    <option value="board_game">board game</option>
    <option value="dvd">DVD</option>
    <option value="all" disabled>All</option>
</div>

<div id="options"></div>

You can view a live demonstration by following this link.

I trust that this resource will set you on the right path towards achieving your desired outcome.

Answer №2

After spending a considerable amount of time working on this since it was first posted, I am pleased to say that I have gained valuable knowledge - thank you.

I have thoroughly examined the Amazon code multiple times and discovered that they have incorporated the option within a span element. Despite my efforts using F12 tools, I have been unable to decipher all the styling applied to these elements.

Returning to basics, I recalled that one common method to achieve variable width is by utilizing a "span" tag - hence, I placed the selected text inside a span.

Furthermore, I found that performing advanced styling on an option element is extremely challenging, if not impossible. Therefore, the option element serves solely for selection purposes - it is added to the div when required and removed afterwards.

For reference, you can view the FIDDLE.

JS

$myoption = "<select class='myselect'><option>selection</option><option>Small</option>                <option>Medium</option><option>Laaaaarge</option><option>Really Looooong</option></select>";

$('.bigdiv').on('click', function(){
    if( $('.bigdiv > .myselect' ).length > 0 )
      { 
       return;
       }
     else
      {
       $('.bigdiv').append($myoption);
       console.log('appended');
       }
});

$( document ).on('change','.myselect', function(){
    console.log('change');
    var myselection = $('.myselect').val();
    console.log('Selection =' + myselection);
    $('.myspan').html( myselection );
    $('.myselect').remove();    
});

$('.remove').on('click', function(){
    $('.myselect').remove();    
});

The developers at Amazon certainly showcase creativity and expertise in their work. It would be fantastic if one of them could provide us with some guidance without revealing any confidential information or trade secrets!

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

Retrieving the return value from an AJAX call in C# using asynchronous methods

When it comes to retrieving a value using Ajax on the client side, I rely on this JQuery function: $.ajax({ type: "POST", url: "/my-page.aspx/checkout", contentType: "application/json; charset=utf-8", dataType: "json", success: functio ...

Issues with AngularJS UI Router functionality are being experienced specifically on localhost

What is causing the discrepancy in UI-Router functionality between JSFiddle and localhost? The localhost link is http://127.0.0.1:54046/preview/app/index.html. Have I overlooked something crucial here? There are no visible JS errors present in the console. ...

In order to ensure accuracy, the 'to' date must always be after the '

By default, when selecting a start date, the end date should be displayed as greater than the start date. However, in my current code, if I select the start date, the end date is set to be the same as the start date. Below is my code snippet. Thank you in ...

What is the best way to pass the reference of the p tag every time the button is clicked?

This is the code I used to create a button: <button type="submit" id="likebtn" onclick="likedpost(this) " data-postid="<%=blog._id%>" data-author="<%=user.username%>">Like</button> ...

What is the best way to enable users to include additional choice information?

I have a dropdown list where the user can select an option, and based on their selection, specific form inputs are displayed. Here is the HTML code: <select id="relative" name="relative"> <option>Choose a relative</option> <o ...

Develop a custom chat feature in HTML with the powerful VueJs framework

Currently, I've been developing a chat plugin for HTML using VueJs. My dilemma lies in creating a versatile plugin that can seamlessly integrate into any website. My ultimate goal is to design a plugin that can be easily deployed on various websites ...

Any suggestions on resolving the issue of a white background in the Spotify embed code?

<iframe src="https://open.spotify.com/embed/track/6wsqVwoiVH2kde4k4KKAFU?utm_source=generator" width="500" height="100" allow="autoplay; clipboard-write; encrypted-media; fullscreen; picture-in-picture" loading=&q ...

Is it just me, or does exiting and returning to a photo gallery seem to magically increase the number of pictures you see when you click the Previous/Next photo button? Can anyone explain this

I am in the process of developing a photo gallery application to enhance my understanding of dynamic content. Take a look at the following URL to gain a better insight: You can also check out the code on Codepen for a deeper look. Despite some styling is ...

Using the inline calendar feature of Bootstrap 3 Datepicker to easily select and capture dates

I've been struggling to extract the selected date from my bootstrap 3 datepicker, and despite attempting to follow the documentation, I still can't grasp it. Here's what I tried: <div id="datetimepicker"> <i ...

Guide to generating customized CSS styles on-the-fly in Vue (similar to Angular's dynamic styling capabilities)

When working with Angular, we have the capability to dynamically set CSS properties. For example: <style ng-if="color"> .theme-color { color: {{color}}; } .theme-background-color { background-color: {{color}}; } .theme-border-color { border-color: { ...

Implementing CSS Pre-loading in an Angular Application with Webpack and Heroku

My current setup involves an Angular application (v4.0.1) with webpack deployed on Heroku. I have a loading spinner in place to show while the app is loading, and it works well locally. However, when deployed on Heroku, the loading spinner (specifically th ...

Creating a button in HTML that performs a POST request without redirecting involves using specific code techniques

Looking for a way to create an HTML button that triggers a POST request to a quick route with parameters passed through req.params. The challenge is preventing the button from redirecting me to the route when clicked, but instead staying on the same page w ...

What is the best way to create a website where images align perfectly with stacked cards?

Having trouble aligning the image on the right side of my website with two cards on the left side. Here is an example of what I'm aiming for: (https://i.sstatic.net/fBvTQ.jpg)](https://i.sstatic.net/fBvTQ.jpg) This is the current code: <!doctyp ...

Scroll the content of a div to the bottom using JavaScript

I'm facing a situation with my code: function scrollme(){ dh=document.body.scrollHeight ch=document.body.clientHeight if(dh>ch){ moveme=dh-ch window.scrollTo(0,moveme) } } However, I am looking for a way to make it scroll only within a specific d ...

Having difficulty removing whitespace from JavaScript code

Struggling to align a div using Javascript on my professor's website to match the spacing of the rest of the site. Despite attempts at adjusting margins and following suggestions from other Stackoverflow.com threads (e.g. CSS: Center block but left al ...

What is the best way to ensure that CSS links resolve properly when incorporating a PathInfo value?

Having an issue with my asp.net 3.5 app. Whenever I try to add a value to the URL for Request.PathInfo, it seems like I lose all connections in the head section because the paths are resolved as relative. This is how the master page appears: <head id= ...

Having trouble retrieving JSON data due to a CORS or callback error

I am attempting to retrieve JSON data from a REST API, but when making an AJAX request with the dataType parameter set as jsonp, I encounter an error stating that the jQuery 'callback was not called'. The error message reads: Error: Status: pa ...

Showing an array in tabular form using Angular

I have a single-element list that appears as shown below view image of array and contents My goal is to present the data in a table with headers for Author Name and Title. However, my current code displays all the titles in one row instead of creating se ...

"Troubleshooting issue with jQuery failing to identify PHP variable within an if

I have managed to implement a code that utilizes jQuery and PHP session to add items to the cart. Everything is working smoothly except for displaying the status of the action, such as "Added to cart" or "Updated". The message about the status is stored in ...

How can I combine an onkeypress and onclick event listener in one method?

I have two inquiries, somewhat intertwined. 1) Is it feasible to merge the 2 functions below into a more efficient function, or do I need to create a function and then call it in both event listeners? input.addEventListener("keyup", () => { if (eve ...