Posts Tagged: jQuery

Simple Combobox — jQuery плагин

Этой весной впервые поработал немного фрилансером, мне нужно было сделать форму, в которой было несколько элементов с автокомплитом. Элементы зависели друг от друга (речь шла о заполнении формы адреса по КЛАДР). Я решил, что будет проще набросать собственный механизм для автокомплита и поначалу оформил это как набор лисенеров, управляя этими компонентами и меняя их данные вручную. Но затем, доделав работу до конца, подумал, что было бы здорово сделать такой компонент jQuery плагином. В итоге поулчилась вот такая штука.

Simple Combobox jQuery plugin

This spring it was the first time I worked as a freelancer. My main task was scripting a form with autocomplete elements. These elements were connected with each other. I decided it would be easier to work around own mechanism of autocomplete combobox component. The first thing I did was a simple html markup and several listeners. I managed comboboxes (primarily refilling and setting as disabled) manually. After I finished the job I thought about making a jQuery plugin from the stuff. Finally I ended up with this.

About table with `display: block` and `overflow-y: auto`

Few days ago my college and I had a page with an extra wide table on it which breaked the page body that is the horizontal scroll appeared on the whole page. We solved the problem with adding the following style on the table: { display: block; overflow-y: auto; max-width: 10px /* any low value here */ }.

But as you may know the tables are not supposed to wear display: block CSS declaration and that was why we failed trying to create something universal for all the tables.

We decided we have to check if the table is extra wide or not and found a quite simple solution, this small: jquery plugin from the answer:

$.fn.hasOverflow = function() { 
    var $this = $(this); 
    var $children = $this.find('*'); 
    var len = $children.length; 
 
    if (len) { 
        var maxWidth = 0; 
        var maxHeight = 0 
        $children.map(function() { 
            maxWidth = Math.max(maxWidth, $(this).outerWidth(true)); 
            maxHeight = Math.max(maxHeight, $(this).outerHeight(true)); 
        }); 
 
        return maxWidth > $this.width() || maxHeight > $this.height(); 
    } 
 
    return false; 
};

We edited it first to make it taking only width in account and then used it in the following way: $('body').hasOverflow().

But it did not work somethimes (probably something more has been changed on the page) and what is also bad thing is that it selects so huge amount of elements on a big pages that it really impacts the performance. But the next day we started to solve it again and in a few minutes we came with a very simple solution:

$(window).width() < $('body')[0].scrollWidth

It works fine by now! We needed just to sleep on it

Про table с `display: block` и `overflow-y: auto`

Недавно была у нас страничка, там появлалась очень широкая таблица, которая разрывала страницу, т.е. заставляла появиться горизонтальный скролл на body. Мы решили эту проблему добавлением стиля на таблицу, а именно { display: block; overflow-y: auto; max-width: 10px /* любая маленькая величина */ }.

Но как известно, таблицы не предназначены для того, чтобы на них вешался display: block, поэтому несмотря на многочисленные попытки сделать что-то универсальное, у других, более узких таблиц, возникли проблемы.

Мы решили, что надо определять, рвёт ли таблица страницу, или не рвёт.

Тут же нашли решение – вот такой компактный jquery-плагин здесь:

$.fn.hasOverflow = function() { 
    var $this = $(this); 
    var $children = $this.find('*'); 
    var len = $children.length; 
 
    if (len) { 
        var maxWidth = 0; 
        var maxHeight = 0 
        $children.map(function() { 
            maxWidth = Math.max(maxWidth, $(this).outerWidth(true)); 
            maxHeight = Math.max(maxHeight, $(this).outerHeight(true)); 
        }); 
 
        return maxWidth > $this.width() || maxHeight > $this.height(); 
    } 
 
    return false; 
};

Мы подправили его так, чтобы рассматривалась только ширина и использовали его следующим образом: $('body').hasOverflow().

Однако в некоторых случаях он не срабатывал (может быть ещё что-то другое изменилось на странице) и кроме этого не очень приятно, что выборка элементов может быть чересчур громоздкой – это может даже влиять на тормознутость страницы. Но на следующий день мы начали думать над этим заново и очень скоро пришли к очень простому методу проверки:

$(window).width() < $('body')[0].scrollWidth

Пока исправно работает! Утро вечера мудренее