Показаны сообщения с ярлыком jquery. Показать все сообщения
Показаны сообщения с ярлыком jquery. Показать все сообщения

пятница, 15 июня 2012 г.

jQuery: "name.replace is not a function" error

It's a very widely known error, since jQuery 1.0 probably. I'll describe he solution en English, because there aren't any English manual for it too.

If you implement the OOP inheritance in JavaScript using this very famous code:

Object.prototype.Inherits = function(parent)
{
 if(arguments.length > 1)
  parent.apply(this, Array.prototype.slice.call(arguments,1));
 else
  parent.call(this);
}

Function.prototype.Inherits = function(parent)
{
 this.prototype = new parent();
 this.prototype.constructor = this;
}

fadeIn() and fadeOut() will cause this error :-(.

Anyway, this version of inheritance isn't so good at all, because it breaks JavaScript foreach-like for too, adding 1 more element "Inherits" to every array.

But what if you have to use it? Is there any way to fix?

Firstly, update this implementation to make it safe:

Object.prototype.Inherits = function(parent)
{
 if(!parent || typeof(parent.call) != "function")
  return;
 if(arguments.length > 1)
  parent.apply(this, Array.prototype.slice.call(arguments,1));
 else
  parent.call(this);
}

Function.prototype.Inherits = function(parent)
{
 this.prototype = new parent();
 this.prototype.constructor = this;
}

Then update jQuery.js (is you have a min version, replace it with full one). Find "getComputedStyle = function( elem, name ) {" and add after first 2 lines:

getComputedStyle = function( elem, name ) {
 var ret, defaultView, computedStyle, width,
  style = elem.style;
 //Add this:
 if(typeof(name) != "string")
  return name;
 //-----

And it will work fine :-)

среда, 13 июня 2012 г.

JavaScript: Receiving GET params of url

Как прочитать в JavaScript параметры, которые идут в URL сразу после ? и имеют вид key=value?

Внимательно вчитаться в образец и сделать ещё удобней:

$.extend({
 getUrlVars: function(){
  var vars = [], hash;
  var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
  var hashesLength = hashes.length;
  var i = 0
  while(i < hashesLength)
  {
   hash = hashes[i].split('=');
   vars.push(hash[0]);
   vars[hash[0]] = hash[1];
   i++;
  }
  return vars;
 },
 UrlVars : null,
 getUrlVar : function(key) {
  if(!key)
   return null;
  if(!this.UrlVars)
   this.UrlVars = this.getUrlVars();
  if(typeof(this.UrlVars[key]) == "undefined")
   return null;
  else
   return this.UrlVars[key];
 }
});

И теперь в любом месте вызываем $.getUrlVar('key') и получаем этот параметр. Если параметра не было - вернёт null.

понедельник, 17 октября 2011 г.

Продолжаем писать слайдер

Обещанный рассказ про скрипт для слайд-шоу.

Сначала определим классы для самого слайдера и для каждого изображения внутри.

function SimpleSlider(width, height, duration){
 this.type = "SimpleSlider";
 this.width = width;
 this.height = height;
 this.duration = (duration) ? duration : 1000;
 this.images = new Array(); //картиночки
 
 this.imgprefix = 'slider-img-';
 this.currimage = 0;
}
function SimpleSliderItem(url, width, height, itemid){
 this.type = "SimpleSliderItem";
 this.url = url;
 this.width = width;
 this.height = height;
 this.itemid = itemid;
}

Добавляем изображение (slider.addImage("..."), разумеется). Перед добавлением кэшируем его, создавая объект типа Image. Этот объект хорош разве что тем, что то, что попадает в его src, будет обязательно прокешировано. Как вставить его на страницу - загадка. Поэтому заполняем images нашим собственным типом и не забываем, что добавлять больше 9999 картинок - нельзя :):

SimpleSlider.prototype.addImage = function(url) {
    if(this.images.length >= 9999)
       return;
    //Caching
    var Image1= new Image(this.width,this.height);
    Image1.src = url;
   //Appending
    this.images.push(new SimpleSliderItem(url, this.width, this.height, this.images.length));
};

SimpleSlider.prototype.insertImage = function(id) {
    if (this.images.length > id){
  var imgElem = document.createElement('img'); 
  imgElem.setAttribute('id', this.imgprefix + id);
  imgElem.setAttribute('class', 'slider-block');
  
  imgElem.setAttribute('src', this.images[id].url);
   
  imgElem.setAttribute('style', 'width: ' + this.images[id].width + '; height: ' + this.images[id].height + '; z-index: ' + (this.images.length - id) + ';');
  return imgElem;
 } else {
  return null;
 }  
};

Вставить все, одно под одним:

SimpleSlider.prototype.insertImages = function(imgElem) {
 imgElem.setAttribute('style', 'width: '+this.width+'; height: ' + this.height + ';');
    for(var img in this.images)  
 {
  var elem = this.insertImage(img);
  if(elem)
   imgElem.appendChild(elem);
 }
};

И вот настало время сделать сам слайдер. Какое изображение следующее - он узнают из функции nextImageId(), а текущее - currImageId(). Если бы это был C#, мы бы оформили их как параметры класса.

В changeImage применяем jQuery. Сначала находим то, что надо и то, на что его менять - а потом меняем. Правда, возникает проблема: в 1-ой картинке z_index больше, чем в последней, и если сделать ей show, то она просто прыгнет наверх безо всякого fade. Поэтому мы ставим последней по счёту картинке z-Index в 9999 (поэтому добавлять можно не больше 9998 изображений), в currImage.fadeOut встроили небольшую callback функцию, которая возвращает z-Index обратно:

SimpleSlider.prototype.nextImageId = function() {
 if(!this.images.length)
  return null;
 this.currimage++;
 if(this.currimage >= this.images.length)
  this.currimage = 0;
 return "#" + this.imgprefix + this.currimage;
};

SimpleSlider.prototype.currImageId = function() {
 if(!this.images.length)
  return null;
 return "#" + this.imgprefix + this.currimage;
};

SimpleSlider.prototype.changeImage = function() {
 var currImage = $(slider.currImageId());
 var nextImage = $(slider.nextImageId());
 isLastItem = !this.currimage;
 if(isLastItem)
  currImage.css('z-Index', '9999');
 currImage.fadeOut(this.duration, function() {
   if(parseInt(currImage.css('z-Index')) == 9999)
    currImage.css('z-Index', '1');
  });
 nextImage.show();
};

вторник, 11 октября 2011 г.

JavaScript: Простое слайд-шоу

На главной странице сайта бюро переводов КонтактЧайна недавно появилось новое слайдшоу. Быстрое и настраивается легко. Написал его я. JavaScript и чуть-чуть jQuery.
После запуска нужно, чтобы функция changeImage() вызывалась раз за разом через определённые промежутки времени. В коде это выглядит так:

var slider = new SimpleSlider(640, 250);

function sliderTimer() {
 slider.changeImage();
 t=setTimeout("sliderTimer()",1000);
}
$(function(){
    slider.addImage("image1.jpg");
    slider.addImage("image2.jpg");
    slider.addImage("image3.jpg");
    slider.insertImages(document.getElementById("slider_simple"));
    sliderTimer();
});
Дальше я расскажу о том, как устроен этот скрипт изнутри.