Saturday, August 18, 2012

blinking loader with javascript

Recently saw a pretty simple ajax-loading image on workopolis.com. It's shown to visitors below the article text while comments are loading. For example you can see it in this article.


Here it is a easy gif file: 

So i decided to do the same with only html and javascript. 
And here is a JSFiddle - http://jsfiddle.net/a7bkU/44/

Actually the parameter in setTimeout call in drawLoader function is a bit tricky - one should play with it a little to customize it to fit a number of blinking circles. In other words, it must be small enough not to make all circles blink at the same time.

HTML
<div class="loading"></div>​

CSS
.load-circle {
    padding:8px;
    background:#666;
    border-radius: 10px;
    display:inline-block;
    margin:5px;
}
.loading {
 margin:10px;
 padding:10 20px;
}
​
JS
drawLoader(3, $('.loading'));

function drawLoader(n, element) {
    //draw loading circles
    for (i=0; i<n; i++) {
        $(element).append('<div class="load-circle" />');
    }
    //for each start a blink action with apropriate time lag
    $.each(jQuery('.load-circle'), function(index, item){
        setTimeout(function(){
            blinker.call(item, true);    
        }, index*400);
    });
}

function blinker(dir){
    //needed for recursive calls
    //knowing in which direction
    if(dir) {
        $(this).animate({opacity: 0.25}, 800, function(){
            blinker.call($(this), !dir);
        })    
     } else {
         $(this).animate({opacity: 1}, 800, function(){
            blinker.call($(this), !dir);
        })     
     }
}

Thursday, August 9, 2012

как надо и как не надо писать в jQuery

В целом статья для начального уровня, но изложение без нервов и понятное.

1. Обработчики событий групп элементов

неэкономично, неправильно
$('.comment a.delete').click(function(){ // });

правильно, метод .on c jQuery 1.7
$('body').on('click', 'a.external', function(e) { // });

2. Ajax вызовы

неправильно, путаница
$.post(url, data, function(data) { // }, 'json').error(function() { /// });

вариант решения с общим обработчиком ошибок
$.ajaxSetup({ error: function() { // } });

читаемый и понятный вариант
$.ajax({ type: "POST" url: url, data: data, dataType: "json", success: function(data) { // }, error: function() { // } })

3. Namespaced events - если нужно независимо добавлять и удалять обработчики на один и тот же элементhttp://docs.jquery.com/Namespaced_Events

Friday, August 3, 2012

блоки кнопок-переключателей - Segmented Radio Buttons

Такой тип контролов с сгруппированными кнопками, выполняющими роль переключателей/фильтров имеет четкое название - Segment Control в iOS или вообще в среде разработчиков проектировщиков называется Segmented Radio Buttons. Такую функциональность можно реализовать out of the box в:
 jQuery UI : Buttons with checkbox - http://jqueryui.com/demos/button/#checkbox
делается с помощью такого кода:

 $('#SELECTOR').buttonset();

<div id="SELECTOR">
<input type="checkbox" id="check1" /><label for="check1">One</label>
<input type="checkbox" id="check2" /><label for="check2">Two</label>
<input type="checkbox" id="check3" /><label for="check3">Three</label>
</div>


А готовые наборы прототипов для верстки веб-интерфейсов предлагают готовое решение лишь для отображения таких блоков, но за их реакцией на действия пользователя и внешним видом пока придется следить самим.

Wednesday, August 1, 2012

Не могу не украсть эту картинку с одной из стартаперских групп на facebook.
Any occasion is an opportunity!

значения ширины экрана для media queries в css


  1. /* телефон в вертикальном положении и прочее */
  2. @media (max-width: 480px) { ... }
  3.  
  4. /* телефон в горизонтальном положении или планшет в вертикальном */
  5. @media (max-width: 767px) { ... }
  6.  
  7. /* планшет в горизонтальном положении или маленький настольный компьютер */
  8. @media (min-width: 768px) and (max-width: 979px) { ... }
  9.  
  10. /* большой стационарный компьютер и выше */
  11. @media (min-width: 1200px) { ... }

Отсюда: http://twitter.github.com/bootstrap/scaffolding.html