8 tecniche jQuery utili

8 tecniche jQuery utili

In questo articolo vorrei presentare otto delle tecniche jQuery che uso più spesso durante il mio lavoro di sviluppo sui siti web e che ritengo più utili. Le presento in questa sede in quanto mi sembra che molto spesso perdiamo tempo nella ricerca di soluzioni sul web che spesso si rivelano assolutamente inadatte.

1. Aumentare la performance dei selettori

Usiamo il contesto del wrapper $():


$('p', '#test').each(function() {

  //...

});

2. Uscire da un ciclo each()

Possiamo uscire da un ciclo each() usando l'istruzione return per lavorare solo su un determinato numero di elementi:


$('p', '#test').each(function(i) {
  
  //...
  
  return i < 5;
});

3. Selezionare l'opzione scelta di un elemento select


var optionChosen = $('select[name=options] option:selected', 'form').val();

4. Creare un'animazione ripetuta nel tempo senza setInterval()


var timer = setTimeout(function() {


  var element = $('#test');
  
  if(element.height() == 100) {
  
    element.animate({
      height: 50
    }, 1500);
  
  } else {
  
    element.animate({
      height: 100
    }, 1500);
  
  }

  setTimeout(arguments.callee, 1500);

}, 500);

5. Serializzare solo i campi dei form voluti


(function($) {


  $.serializeSelectedFields = function(options) {
  
    var defaults = {
    
      form: 'form',
      fields: ':input'
    
    };
    
    var serializedValues = [];
    var separator = '&';
    var delimiter = '=';
    
    options = $.extend(defaults, options);
    
    
    $(options.fields, options.form).each(function() {
    
       var element = $(this);  
       var name = element.attr('name');
       var value = element.val();
       
       var serializedValue = name + delimiter + value;
       
       serializedValues.push(serializedValue);
    
    
    });
    
    
    return serializedValues.join(separator);
  
  
  };


)(jQuery);

6. Ottenere gli offset delle slide in uno slideshow


var getSlidePositions = function(slides, context) {

  slides = slides || 'div.slide';
  context = context || '#slideshow';

  var positions = [];
  
  $(slides, context).each(function(i) {
  
    var left = $(this).position().left;
    
    positions[i] = left;
  
  });

  return positions;

};

7. Gestire le animazioni su mouseover/mouseout


$(element).hover(function() {

  $(this).stop(true, true).animate({
    height: 100
  }, 'slow');

}, function() {

  $(this).stop(true, true).animate({
    height: 200
  }, 'slow');

});

8. Bloccare un evento dopo un n numero di volte


var n = 0;
$(element).bind('click', function(event) {

  n++;
  
  var eventType = event.type;
  
  if(n == 3) {
  
    $(element).unbind(eventType);
  
  }



});
Torna su