GithubHelp home page GithubHelp logo

baron's Introduction

Build Status Join the chat at https://gitter.im/Diokuz/baron

You cannot change the world, but you can change a scrollbar!

Baron demo

Baron — a small, fast and crossbrowser custom scrollbar with native system scroll mechanic.

See also react-baron.

Features

  • Doesn't replace native system scroll mechanic.
  • Customizable scrollbar design with full CSS support.
  • Does not depend on external libraries (since v3).
  • Can be inited on hidden blocks
  • Vertical, horizontal and bidirectional scroll
  • Infinite scroll
  • Nested scrollers

Baron does not replace the native scrollbar, just hides it. This guarantees scrolling will work in any browser.

1. Hiding system scrollbar

  • Include baron.js and some css:
<script src="baron.js"></script>
<style>
    ::-webkit-scrollbar { /* for Mac OS X support */
        width: 0;
    }
</style>
  • Initialize baron on your scroller:
baron('.my-scroller');

2. Making your own custom-designed scrollbar

You can do everything you want with CSS of your custom scrollbar. There are some required and recommended css rules (see base css) – do not forget to use them. You can also use predefined skins.

Webpack

Just import baron and use it:

import baron from 'baron';
// or: const baron = require('baron');

baron({ scroller: ... });

Version for development

Note, that baron.js is a development version. It contains additional code and log messages, to make the development process easier.

baron.min.js is a production-ready version: weight less, works a little bit faster.

Nested scrollers

Baron supports nested scrollers. To make scrollers happy, follow the rule:

  • Initialize baron instances from ancestor to descendant scrollers order.

Third World War will not begin if you break that rule, but there may be some bad user-experience with baron-instances updates (when size of one scroller depends on size of another). See /demo source.

Browsers support

Baron uses two old CSS 2.1 technologies: 1) overflow: scroll 2) overflow: hidden.

Chrome logo Firefox logo Internet Explorer logo Opera logo Safari logo Android browser logo
8+ ✔ 3.6+ ✔ 10+ ✔ 11.5+ ✔ 5.1+ ✔ 4+ ✔

Wanna support ie6 and Opera 9? Try baron@2 version + jQuery. Version 3+ uses classList API and style attribute.

3.0 migration

  1. Make sure you are satisfied with new supported browser list.
  2. Remove $ and event params if any. You also could remove jQuery from your page.
  3. Make sure you have one html node per one initialization: multi-baron not supported.
  4. pull plugin removed, so you cannot use it anymore. But you can add it manually.

2.0 migration

impact param default value changed to scroller for all directions. That impact horizontal scrollbars.

If you use % cross-paddings (padding-left and padding-right for vertical direction) for scroller, it will be buggy in Mac OS X Firefox because of need for extra-padding to support it. Use pixels instead, or make html-container inside scroller.

Also, checkout changelog.

1.0 migration

If you have any problems, just set cssGuru option to true.

License

MIT.

baron's People

Contributors

alexluke avatar bayandin avatar bezdonas avatar chrisk12345 avatar darkwebdev avatar diokuz avatar dolbyzerr avatar emilmoe avatar faceleg avatar gitter-badger avatar glenswift avatar grabus avatar klimril avatar mialinx avatar ndragomirov avatar philraj avatar pseidemann avatar semenov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

baron's Issues

Buggy on iPad (and iPhone possibly)

  • native scrollbar is visible on scroll
  • scrollbar is not animated until scrolling animation is finished (native one animated instead)
  • scrollbar is not accessible for the touch events.

Removing Baron

What is the way to cleanup baron instance properly?
Especially window resize handler?

There's need to be something like "unbind" or "remove" method.

I'm using Backbone.Marionette and if I want to remove any View I need cleanup baron instance.
For now $._data(window, "events").resize still keeps baron update handler, and its growing for every time baron is initialized, which happens very often in dynamic single-page application.

Системный скролл в FF в OSX

Есть небольшая проблемка в FF у пользователей маков - дублируется скролл, причем даже в ваших примерах со статьи и комментов с хабра.
Есть предположения, как бы ее можно было разрешить?

Совместимость с ангуляром

Вопрос такой. У меня есть список отсортированный по датам, соответственно нужно выводить в хидере дату, далее относящиеся к данной дате элементы списка.
Использую ангуляр, но тот не поддерживает в шаблонах циклы без создания элемента. Поэтому пришлось сделать пустой родительский див и в нем крутить цикл по датам. Можно настроить барон чтобы он корректно работал с такой структурой, или как-то поместить список внутри дива с хидером:

< div class="scroller-wrap__overlay">
< div ng-repeat="item in items">
< div class="header">
{{ item.date}}
< /div>
< ul>
< li ng-repeat="elem in item.list">{{elem}}
< /ul>
< /div>
< div class="scroller__bar">
< span>
< /div>
< /div>

Обновление сролла

var scroll = baron($('.t'), {
    scroller: '.scroller',
    container: '.container',
    bar: '.scroller__bar'
});

Не получается выполнить scroll.u(), как указано в документации

console.log(scroll);
// [baron.init]
//   0: baron.init
//     updateScrollBar: function () {
//     viewport: function () {
//     __proto__: Object
//   length: 1
//   __proto__: Array[0]

Удалось правильно ли использовать?

scroll[0].updateScrollBar();

Или что-то не так делаю?

Custom eventHandler in params:

We have this construction in params:

event: function(elem, event, func, mode) {
if (mode == 'trigger') {
mode = 'fire';
}
bean[mode || 'on'](elem, event, function);
}

But i don't understand , what i should will do , if i want use 'sizeChanges' (your type of event...) i think something like this :
event: function(elem,event,function,mode) {
if(event=="sizeChanges") {
scroll.update();
}

}
Yes??? and if possible , can you give me differents simple examples of work with manager of events.

Width of div.scroller doesn't recalculate after window resize

Hi!
If I trigger $.baron.u() on window.resize event scrollbar just disappears, but div.scroller's width is correct.
If I just call $('div.wrapper').baron(); div.scroller's width doesn't recalculate.

Возможно, мой английский кривой. В общем, барон устанавливает ширину для div.scroller. Если я начинаю вешать события на ресайз окна, то при вызове $.baron.u() ширина пересчитывается, но пропадает сам скроллбар, если же заново вызываю $('div.wrapper').baron(), то ширина скроллера остаётся в старой позиции и приходится сбрасывать вручную.

Перестал работать без jquery

На странице /test/index.html в хроме перестал работать пример (No jQuery (qwery, bean and bonzo)), отваливается с ошибкой Uncaught TypeError: undefined is not a function core.js:48.

Update() method does not recalculate the width

Здравствуйте.

Wrapper вложен в блок с нефиксированной шириной. Метод update() или trigger('sizeChange') не приводит к пересчету значения атрибута width, полученного при инициализации.

Выставление height у scroller при горизонтальной прокрутке

Не могу понять зачем выставляется height у scroller div-а, если прокрутка происходит горизонтально. У меня высота контента меняется динамически и я не могу придумать как попросить baron не выставлять высоту в style.

А вообще, спасибо за хороший плагин.

Update: использую angularjs как средство вывода элементов, возможно baron смотрит на высоту, когда контент еще не успел прорисоваться. Так как изменение высоты в style происходит, но высота scroller выставляется всегда меньше, чем высота контента.

fix plugin: params update

Будет круто если барон научится переписывать значения параметров у заиниченого плагина, например изменить флаг параметра limiter для fix плагина.

Support mobile devices

Please add methods for mobile devices

iphone\ipad - all works, but in androids smartphones doesn't touch events..

Uncaught ReferenceError: jQuery is not defined

8: $ = jQuery, // Trying to use jQuery

if jQuery undefined application is down :(

i am use this code

var scroller = baron({
                    root:iElement[0],
                    scroller: '.baron-scroller',
                    container: '.baron-container',
                    bar: '.baron-scroller__bar',
                    track: '.baron-scroller__track',
                    $: function(selector, context) {
                        return angular.element(selector, context);
                    }
                });

trackOnCls?

How to display/hide track outside scroller?

fix + pull first header blinking bug

Проблема связана с обновлением барона после отработки pull на первом заголовке - остается класс фиксации.

Возможно нужно отключить pull когда контент ниже вьюпорта (нет скролла).

Controls

Up, Down, Left, Right buttons.

Event when start/stop drag of scrollbar

I have a situation where both a div using Baron and an iframe are on the same page. When somebody drags the scrollbar and hovers over the iframe Baron will not be able to track the mouse.

I guess this problem is insolvable and due to the nature of the iframe. To resolve it I want to show an hidden frame over the frame whenever somebody is dragging. But.. I do not know which events I can/should use in order to do so. Are there dragstart/dragstop events on the scrollbar?

Ajax requests support

scrollbar size shuold adjust not only on window resize, but also on content change via ajax requests

Height autoupdate bug

Problem with automatic elevation change when the height varies with transition or css-animation.

А теперь без мексиканского английского :)
Баг с обновлением высоты, при использовании transition (и видимо css-animation).

RTL support

Планируется ли добавить поддержку RTL?

Wrong scroller init when broken selector used

jQueryMode выставляется в false, и поэтому барон думает что корня нет и начинает искать скроллер по всему документу - находит первый попавшийся.

barOnCls is only added on update() but not on baron()

the css class name for scroller barOnCls is not added to the scroller when initializing baron for the first time when calling baron(). it is only added when baron makes an update or when I call update() manually.

is this by design?

this is causing the bug that the scroller track isn't visible until an update is performed even when the content is high enough

infinite list + baron

It's not clear how can I do inifite list with baron scrollbars. Currently I'm using this approach:

$list.find('.scroller').scroll(function () {
var tweak = 100
var $bar = $list.find('.scroller__bar')
if ($bar.position().top + $bar.height() + tweak > $scroller.height()) {
//append items
}
}

I don't want to use scroller__ba, because on ipad I would like to use native scrolls.

Have you ideas of how can it be done?

Thanks!

Bug when content height is not auto

I need to have responsible container height (95%), but baron did't correctly work with it (scrollbar becomes invisible). It works only when content height is auto:

.scroller .content {
  height: auto;
}

But this ruins my resposible layout. What can I do with it? Many thanks.

IFrame bug

Uncaught TypeError: Cannot call method 'apply' of undefined
this[i].update.apply(this[i], arguments);

PT Sans inaccurate sizes calc

При использовании этого шрифта приходится обновлять барона - походу проблема в подгрузке шрифта в ходе которой размеры меняются.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.