Change Select style using jQuery. IkSelect - the perfect plugin for styling selects Beautiful select jquery

Home / Breakdowns

Attention! Further development and support for the plugin has been stopped due to the fact that it is now part of .

One of the most unpleasant (and I would even say terrible) things in web development is the layout of html forms. Unfortunately, there is no uniform standard for displaying form elements, regardless of browser and operating system, just as there is no way to customize some of these elements using cascading style sheets.

The following HTML form elements cannot be fully styled:

  • dropdown list ;
  • checkbox ;
  • switch .
  • field for sending a file.

As is already clear from the title of the post, here we will only talk about selects.

There are many ready-made solutions in the form of jQuery plugins for styling drop-down lists. But I (due to the fact that none of the plugins suited me for one reason or another) decided to go by reinventing my own wheel and wrote my own plugin, which I share in this article.

I would like to note right away that this plugin is not suitable for all possible cases of using selects (read the disadvantages).

Demonstration of the plugin

You can see an example of selector styling using my plugin. I designed them without using images.

Advantages
  • When JavaScript is disabled, standard selectors are displayed.
  • The script is small in size, approximately 4 kilobytes.
  • Works in IE6+ and all modern desktop browsers.
  • Displayed inline.
  • Easily styled using CSS.
  • Allows you to set the maximum height for the drop-down list (CSS property max-height).
  • Automatically adjusts the width if it is not specified.
  • Supports mouse wheel scrolling.
  • Has “smart positioning”, i.e. does not go beyond the visible part of the page when opening the list.
  • Can “catch” pressing the Tab key and switch with arrows on the keyboard.
  • Supports the "disabled" attribute.
  • It also works with dynamically added/changed selects.
Flaws
  • Does not support the multiple attribute, i.e. does not allow selecting multiple items (multi-select).
  • Does not support grouping of list items (tag).
  • Does not support switching with arrow keys on the keyboard when the list is opened by clicking the mouse.
Download

The plugin is not available because it is no longer relevant.

jQuery plugin “SelectBox Styler”

Version: 1.0.1 | Downloads: 11103 | Size: 7 KB | Latest update: 07.10.2012

Updates 09/22/2012 Converted the script into a plugin (including a minimized version), and also added support for dynamically adding/changing selects. 10/07/2012 Fixed the behavior of the script when using the onchange method of the tag. Connecting the plugin

If the site does not yet have jQuery enabled, then add the following line before the tag:

Immediately after jQuery, include the file with the script:

(function($) ( $(function() ( $("select").selectbox(); )) ))(jQuery)

Place this code before the tag after the above files.

When changing selects dynamically, you need to fire the refresh trigger, for example:

(function($) ( $(function() ( $("button").click(function() ( $("select").find("option:nth-child(5)").attr("selected ", true); $("select").trigger("refresh"); )) )) ))(jQuery)

HTML code after plugin execution

Its structure looks like this:

-- Select --

  • -- Select --
  • Point 1
  • Point 2
  • Point 3
-- Select -- Item 1 Item 2 Item 3

CSS classes used to style the selector

To issue selects with using CSS, use the following classes:

.selectboxparent container for the entire select
.selectbox .selectselect in collapsed state
.selectbox.focused .selectfocus on select when Tab key is pressed
.selectbox .select .textnested tag for a collapsed select in case of inserting a background image using the “sliding door” technique
.selectbox .triggerright side of the collapsed select (conditional switch)
.selectbox .trigger .arrowsubtag for radio button (arrow)
.selectbox .dropdownwrapper for dropdown list
.selectbox .dropdown uldropdown list
.selectbox liselect item (option)
.selectbox li.selectedselected select item
.selectbox li.disableddisabled (not available for selection) select item
Conclusion

Creating such a script is a rather painstaking task, since you have to take into account many different points. I really hope that no serious bugs will appear. But, if anything, please let me know in the comments.

Hello, Habrausers and just readers. Relatively recently I wondered how to apply styles to the select tag. Everyone wants the styling of the form to match the design of the site, but not everything can yet be described with pure CSS. In this article we will look at a simple example of writing your own select list using CSS and the JavaScript language library - jQuery. I think especially beginners will be interested in this material. Of course, it would be better to write it in native JS, but everyone knows that there would be more lines of code, and it would hardly be clearer.

To be honest, before I started creating the next bicycle, I tried to find a similar solution, but I couldn’t find anything other than spectacular div wrappers for the select tag. And I thought it would be nice to write something simple and necessary. Well, let's begin!

Our plasticine modeling circle involves three files:

  • selectbox.html
  • selectbox.css
  • selectbox.js
Let's look at them one by one. First, let's pay attention to the most simple thing in this example - the layout of the list or the selectbox.html file:

selectbox.html

Month

  • January
  • February
  • March
  • April
  • May
  • June
  • July
  • August
  • September
  • October
  • November
  • December


As you can see from the source html code, our list will prompt us to select a month. Now let's look at the selectbox.css file:

selectbox.css

div#selectBox ( width: 250px; position: relative; height: 50px; border-radius: 3px; border: solid 1px lightgrey; background-color: #fff; color: #333; cursor: pointer; overflow: hidden; transition: .3s; ) div#selectBox p.valueTag ( padding: 15px; cursor: pointer; transition: .2s; height: 40px; ) div#selectBox > img.arrow ( position: absolute; right: 0; width: 50px; padding : 15px; ) /* for Safari, Chrome and Opera users a nice bonus is a stylized scroll bar. */ ::-webkit-scrollbar ( background: transparent; width: 0.5em; position: absolute; ) ::-webkit-scrollbar-track ( background: transparent; position: absolute; z-index: -2; ) :: -webkit-scrollbar-thumb ( border-radius: 100px; background: #888; ) ul#selectMenuBox ( background: #fff; transition: .3s; width: 100%; height: 200px; overflow-y: auto; overflow- x: hidden !important; position: absolute; margin-top: 00px; display: block; ) ul#selectMenuBox > li.option ( color: gray; padding: 10px; ) ul#selectMenuBox > li.option:hover ( color: #333; background: #e1e1e1; transition: .2s; )


There are no particular difficulties here if you know the basics of layout and markup using HTML and CSS3, respectively.

Now on to the goodies! Let's consider source code plugin selectbox() for jQuery, selectbox.js file:

selectbox.js

(function($) ( $.fn.selectbox = function() ( // initial parameters // set the standard height of div"a. var selectDefaultHeight = $("#selectBox").height(); // image rotation angle in div"e var rotateDefault = "rotate(0deg)"; // after pressing the button, a function is triggered in which // the initial height of our div"a is calculated // very convenient for comparison with the incoming parameters (what is set at the beginning of the script). ) $("#selectBox > p.valueTag").click(function() ( // calculating the height of the object using the height() method var currentHeight = $("#selectBox").height(); // checking the condition for matching/ does not match the given height at first, // to understand what to do next if (currentHeight.< 100 || currentHeight == selectDefaultHeight) { // если высота блока не менялась и равна высоте, заданной по умолчанию, // тогда мы открываем список и выбираем нужный элемент. $("#selectBox").height("250px"); // «точка остановки анимации» // здесь стилизуем нашу стрелку и делаем анимацию средствами CSS3 $("img.arrow").css({borderRadius: "1000px", transition: ".2s", transform: "rotate(180deg)"}); } // иначе если список развернут (высота больше или равна 250 пикселям), // то при нажатии на абзац с классом valueTag, сворачиваем наш список и // и присваиваем блоку первоначальную высоту + поворот стрелки в начальное положение if (currentHeight >= 250) ( $("#selectBox").height(selectDefaultHeight); $("img.arrow").css((transform: rotateDefault)); ) )); // also collapse the list when selecting the desired element // and change the text of the paragraph to the text of the element in the list $("li.option").click(function() ( $("#selectBox").height(selectDefaultHeight); $ ("img.arrow").css((transform: rotateDefault)); $("p.valueTag").text($(this).text()); ); ))(jQuery);


There was more code, but we managed to compress it thanks to the css() and height() methods. Designed as a plugin for convenience and repeated use. You can do it the way you like, as long as it works, so I won’t be offended if someone optimizes my crutch. To make a call just connect external file script and call the plugin like this:

$("selector").selectbox();
First, include a call in the ready() method of the document object so that the plugin is loaded after the document is fully loaded. You can find out more about what a jQuery plugin is.

About a year ago, I already did a detailed review of jQuery plugins for styling selects. The result was disappointing, each of them had its own shortcomings, and I could not find what I wanted. Quite a lot of developers responded in the comments, but we all agreed that there is no perfect plugin, and that any of them requires a lot of work with a file.

Recently, Selectik popped up on Habré - a pretty good plugin, but not without its drawbacks. Judging by GitHub, work on it is still underway, but so far it is not very convenient, and its main problems still exist.

Recently, a stranger wrote to me and asked me to test his ikSelect plugin, which he tried to write as close to ideal as possible. I liked the plugin so much that after extensive testing and bug fixing, I decided to write a review of it and put an end to this topic, as well as help a smart developer get onto the hub.

In a nutshell: it can do almost everything that a standard select can do, while being perfectly stylized and adjusted to the specifics of select implementation different browsers. The plugin completely copies appearance native Mac OS X selector, but it can be styled via CSS without any problems.

This is what it looks like when closed:

Like this in open:

Why is it better than the rest? Volume: 11KB

Advantages:

  • works in all browsers (IE6+, FF, Opera, Chrome, Safari), including mobile ones
  • automatically adjusts width
  • always opens to the visible part of the page (so-called “smart positioning”), both horizontally and vertically
  • allows you to set the maximum height of the dropdown list
  • allows you to group options (optgroup)
  • fully controlled from the keyboard (including responding to transitions with Tab, PgUp, PgDown, Home, End)
  • has a selection based on the first letters (not only one, but also subsequent ones)
  • supports scrolling with mouse wheel
  • inserted inline (inline-block)
  • works great with huge lists (1000+ items)
  • leaves the standard select when javascript is disabled
  • has a great API
Flaws:
  • does not allow selecting several items at once (multiselect)
  • does not style the scrollbar of the drop-down list (because it affects the speed too much)
  • doesn't run for beer
Mobile Browsers The plugin styles the field itself, but when clicked, invokes native browser behavior. Tested on iOS (Safari) and Android (2.3 native, Firefox):

In Opera mini, standard selectors remain to avoid page reloading when opening a list. In Opera mobile it works the same as in the desktop version.

Anyone who seriously deals with page layout knows that the styling options for select in CSS are extremely limited. But very often the standard select does not fit into the design at all, so you have to style the select using JavaScript. In fact, in this article we will create our own select using JavaScript.

There are a lot of ready-made plugins, including jQuery ones, that allow you to do all this. But if you don’t need something super complex, then it’s easier to do everything yourself from scratch using pure JavaScript.

First of all, let's create the HTML structure of our future select :




Element 1
Element 2
Element 3



Element 1


Element 2


Element 3




As you can see, there is no select tag here. Now we can style our custom select however we want using CSS:

Select (
background-color: #0ee;
border-radius: 10px;
padding: 10px 0;
width: 200px;
}
.select p(
cursor: pointer;
margin: 0;
padding: 5px 20px;
}
.select p.active (
background-color: #ee0;
}

Of course, you can do whatever you want here. And finally, we need to turn the appearance into select functionality, that is, selecting and highlighting only one element from several, and then submitting it along with the form. To do this we will use JavaScript:

Function select(element) (
var value = element.getAttribute("data-value"); // Read the value of the selected element
var nodes = element.parentNode.childNodes; // Get all other elements
for (var i = 0; i< nodes.length; i++) {
/* Filter out extraneous text and input elements */
if (nodes[i] instanceof HTMLParagraphElement) (
/* Add active to the selected element, erasing this class from all others */
if (value == nodes[i].getAttribute("data-value")) nodes[i].className = "active";
else nodes[i].className = "";
}
}
document.getElementById("my_select").value = value; // Set the hidden field to the selected value
}

The key to implementing select functionality is the hidden field, which stores the value from our select . And this is the value that will be sent when the form is submitted.

This is a simple way to do absolutely any select styling in JavaScript. If you use jQuery, the code will be even simpler.

Of course, the standard select has more functionality. For example, it responds to tab , and you can also use the arrow keys on the keyboard to navigate through elements. But you can also implement all this in JavaScript if necessary.

And the last recommendation. The code used the noscript tag, and this was no accident. Since not everyone has JavaScript enabled, and for the form to work at all for such users, you need to display at least a standard select . And everyone who has JavaScript enabled will see our beautiful select .

When creating a website, every web master tries to make his creation read equally in all browsers, and this sometimes causes trouble. Therefore, in this lesson we will talk about creating and styling a site element such as select or, more simply put, a selection button. We will look at several scripts that will transform a regular element select into a more stylish and functional site control that displays correctly in different browsers. So, let's see what we got...

SOURCES

In this tutorial we will use HTML5, so first of all we create HTML markup, which looks like this:

Create a select element for the site | Demonstration from the website website




Make your choice Select a product Information sheet on web design CMS+templates, plugins Interesting lessons on creating websites RSS news from our blog is always nearby

Next, let's look at some attributes, for example the attribute data are used to combine information in option elements. They contain a product icon and a text description with formatting. Both of these items will appear in our version of the select element.

Now we connect the effects, jQuery checks the element select, and, using data attributes, builds markup that is added immediately after the element select:

Select product

  • JavaScript + jQuery for beginners in video format watch the video presentation
  • PHP + MySQL for Beginners buy
  • WordPress - professional blog in one day download
  • Joomla - professional website in one day buy

Our menu will build an unordered list of items li, which represent each item option from element select.

Now let's look at our JavaScript, which will smoothly animate our element:

$(document).ready(function())( // The select element that will be replaced: var select = $("select.makeMeFancy"); var selectBoxContainer = $("",( width: select.outerWidth(), className : "tzSelect", html: "" )); var dropDown = $("

    ",(className:"dropDown")); var selectBox = selectBoxContainer.find(".selectBox"); // Loop through the original select element select.find("option").each(function(i)( var option = $(this); if(i==select.attr("selectedIndex"))( selectBox.html(option.text());) // Since jQuery 1.4.3 is used, we can access // HTML5 data attributes using the data() method. if(option.data("skip"))(return true; ) // Create a drop-down item according // to the data icon and HTML5 data attributes: var li = $("
  • ",(html: " "+ option.data("html-text")+"" )); li.click(function())( selectBox.html(option.text()); dropDown.trigger("hide"); // When it happens click event, we also reflect // changes to the original select element: select.val(option.val()); dropDown.append(li)); ); select.hide().after(selectBoxContainer); // Bind custom events show and hide to the dropDown element: dropDown.bind("show",function())( if(dropDown.is(":animated"))( return false; ) selectBox.addClass("expanded"); dropDown.slideDown() ; )).bind("hide",function())( if(dropDown.is(":animated"))( return false; ) selectBox.removeClass("expanded"); dropDown.slideUp(); )).bind ("toggle",function())( if(selectBox.hasClass("expanded"))( dropDown.trigger("hide"); ) else dropDown.trigger("show"); )); selectBox.click(function())( dropDown.trigger("toggle"); return false; )); // If you click the mouse button anywhere on the page while the dropDown element is open, // it will be hidden: $(document).click(function())( dropDown.trigger("hide"); )); ));

    Now a small nuance, when creating our element, the original element select saved, it will be hidden using the hide() method. This is no less important, because all changes are reflected in it.

    Then we look at our CSS styles, we will use CSS3, set styles for our element:

    #page( width:490px; margin:50px auto; ) #page h1( font-weight:normal; text-indent:-99999px; overflow:hidden; background:url("../img/your_product.png") no -repeat; width:490px; height:36px; ) #page form( margin:20px auto; width:460px; ) .tzSelect( /* Container for the new select element */ height:34px; display:inline-block; min- width:460px; position:relative; /* Preload background image for dropdown items */ background:url("../img/dropdown_slice.png") no-repeat -99999px ) .tzSelect .selectBox( position:absolute; height:100%; width:100%; /* Setting the font */ font:13px/34px "Lucida Sans Unicode", "Lucida Grande", sans-serif; text-shadow:1px 1px 0 # EEEEEE; color:#666666; /* Using multiple CSS3 backgrounds */ background:url("../img/select_slice.png") repeat-x #ddd; background-image:url("../img/select_slice. png"),url("../img/select_slice.png"),url("../img/select_slice.png"),url("../img/select_slice.png");background-position: 0 -136px, right -204px, 50% -68px, 0 0; background-repeat: no-repeat, no-repeat, no-repeat, repeat-x; cursor:pointer; -moz-border-radius:3px; -webkit-border-radius:3px; border-radius:3px; ) .tzSelect .selectBox:hover, .tzSelect .selectBox.expanded( background-position:0 -170px, right -238px, 50% -102px, 0 -34px; color:#2c5667; text-shadow:1px 1px 0 #9bc2d0 ; )

    This example uses many transparent images that are superimposed one on one. Multiple background images supported in Firefox, Safari, Chrome and Opera. For Internet Explorer and older versions of browsers.

    TzSelect .dropDown( position:absolute; top:40px; left:0; width:100%; border:1px solid #32333b; border-width:0 1px 1px; list-style:none; -moz-box-sizing:border -box; -webkit-box-sizing:border-box; -moz-box-shadow:0 0 4px #111; shadow:0 0 4px #111; ) .tzSelect li( height:85px; cursor:pointer; position:relative; /* Using multiple CSS3 backgrounds */ background:url("../img/dropdown_slice.png") repeat- x #222; background-image:url("../img/dropdown_slice.png"),url("../img/dropdown_slice.png"),url("../img/dropdown_slice.png"); background-position: 50% -171px, 0 -85px, 0 0; background-repeat: no-repeat, no-repeat, repeat-x ) .tzSelect li:hover( background-position: 50% -256px, 0 - 85px, 0 0; ) .tzSelect li span( left:88px; position:absolute; top:27px; ) .tzSelect li i( color:#999999; display:block; font-size:12px; ) .tzSelect li img( left:9px; position:absolute;top:13px)

    Using box-sizing, we need to assign a value to it border-box, this will prevent the overall width from increasing since our fragments are placed inside the element. That's all, our improved selection elements have been created, good luck with your experiments.

© 2024 ermake.ru -- About PC repair - Information portal