PageSourceSearch

https://litgid.com/js/jquery.eislideshow.js

js litgid.com collected 2026-09-24 09:28:53 UTC 12,109 bytes, 418 lines download raw bytes

1(function( window, $, undefined ) {
2	
3	/*
4	* smartresize: debounced resize event for jQuery
5	*
6	* latest version and complete README available on Github:
7	* https://github.com/louisremi/jquery.smartresize.js
8	*
9	* Copyright 2011 @louis_remi
10	* Licensed under the MIT license.
11	*/
12
13	var $event = $.event, resizeTimeout;
14
15	$event.special.smartresize 	= {
16		setup: function() {
17			$(this).bind( "resize", $event.special.smartresize.handler );
18		},
19		teardown: function() {
20			$(this).unbind( "resize", $event.special.smartresize.handler );
21		},
22		handler: function( event, execAsap ) {
23			// Сохраняем контекст
24			var context = this,
25				args 	= arguments;
26
27			// Устанавливаем правильный тип события
28			event.type = "smartresize";
29
30			if ( resizeTimeout ) { clearTimeout( resizeTimeout ); }
31			resizeTimeout = setTimeout(function() {
32				jQuery.event.handle.apply( context, args );
33			}, execAsap === "execAsap"? 0 : 100 );
34		}
35	};
36
37	$.fn.smartresize 			= function( fn ) {
38		return fn ? this.bind( "smartresize", fn ) : this.trigger( "smartresize", ["execAsap"] );
39	};
40	
41	$.Slideshow 				= function( options, element ) {
42	
43		this.$el			= $( element );
44		
45		/***** Изобаржения ****/
46		
47		// Список изобаржений
48		this.$list			= this.$el.find('ul.ei-slider-large');
49		// Пункты списка
50		this.$imgItems		= this.$list.children('li');
51		// Общее количество изображений
52		this.itemsCount		= this.$imgItems.length;
53		// Изобаржения
54		this.$images		= this.$imgItems.find('img:first');
55		
56		/***** Мимниатюры ****/
57		
58		// Контейнер миниатюр
59		this.$sliderthumbs	= this.$el.find('ul.ei-slider-thumbs').hide();
60		// Элементы слайдера
61		this.$sliderElems	= this.$sliderthumbs.children('li');
62		// Выскальзывающий элемент div
63		this.$sliderElem	= this.$sliderthumbs.children('li.ei-slider-element');
64		// Миниатюры
65		this.$thumbs		= this.$sliderElems.not('.ei-slider-element');
66		
67		// Нициализация слайдшоу
68		this._init( options );
69		
70	};
71	
72	$.Slideshow.defaults 		= {
73		// Типы анимации:
74		// "sides" : новый слайд выскальзывает слева или справа
75		// "center": новый слайд появляется в центре
76		animation			: 'sides', // sides || center
77		// Если значение true, то включается автопроигрывание слайдшоу, которое отключается при нажатии на миниатюру
78		autoplay			: false,
79		// Интервал для слайшоу
80		slideshow_interval	: 3000,
81		// Скорость анимации смены слайдов
82		speed			: 800,
83		// Функция перехода для анимации смены слайдов
84		easing			: '',
85		// Процентное соотношение анимации заголовков. Скорость будет определяться по формуле speed * titlesFactor
86		titlesFactor		: 0.60,
87		// Скорость анимации заголвоков
88		titlespeed			: 800,
89		// Функция перехода для анимации заголовоков
90		titleeasing			: '',
91		// Максимальная ширина для миниатюр в px
92		thumbMaxWidth		: 150
93    };
94	
95	$.Slideshow.prototype 		= {
96		_init 				: function( options ) {
97			
98			this.options 		= $.extend( true, {}, $.Slideshow.defaults, options );
99			
100			// Устанавливаем непрозрачность для элементов заголовков и изображений
101			this.$imgItems.css( 'opacity', 0 );
102			this.$imgItems.find('div.ei-title > *').css( 'opacity', 0 );
103			
104			// Индекс текущего видимого слайда
105			this.current		= 0;
106			
107			var _self			= this;
108			
109			// Предварительная загрузка изображений
110			// Добавляем статус загрузки
111			this.$loading		= $('<div class="ei-slider-loading">Loading</div>').prependTo( _self.$el );
112			
113			$.when( this._preloadImages() ).done( function() {
114				
115				// /скрываем статус загрузки
116				_self.$loading.hide();
117				
118				// Вычисляем размер и положение для каждого изображения
119				_self._setImagesSize();
120				
121				// Конфигурируем контейнер для миниатюр
122				_self._initThumbs();
123				
124				// Выводим первый пункт
125				_self.$imgItems.eq( _self.current ).css({
126					'opacity' 	: 1,
127					'z-index'	: 10
128				}).show().find('div.ei-title > *').css( 'opacity', 1 );
129				
130				// Если включено автопроигрывание
131				if( _self.options.autoplay ) {
132				
133					_self._startSlideshow();
134				
135				}
136				
137				// Инициалищируем события
138				_self._initEvents();
139			
140			});
141			
142		},
143		_preloadImages		: function() {
144			
145			// Предварительная загрузка всех больших изображений
146			
147			var _self	= this,
148				loaded	= 0;
149			
150			return $.Deferred(
151			
152				function(dfd) {
153			
154					_self.$images.each( function( i ) {
155						
156						$('<img/>').load( function() {
157						
158							if( ++loaded === _self.itemsCount ) {
159							
160								dfd.resolve();
161								
162							}
163						
164						}).attr( 'src', $(this).attr('src') );
165					
166					});
167					
168				}
169				
170			).promise();
171			
172		},
173		_setImagesSize		: function() {
174			
175			// Сохраняе ширину слайда
176			this.elWidth	= this.$el.width();
177			
178			var _self	= this;
179			
180			this.$images.each( function( i ) {
181				
182				var $img	= $(this);
183					imgDim	= _self._getImageDim( $img.attr('src') );
184					
185				$img.css({
186					width		: imgDim.width,
187					height		: imgDim.height,
188					marginLeft	: imgDim.left,
189					marginTop	: imgDim.top
190				});
191				
192			});
193		
194		},
195		_getImageDim		: function( src ) {
196			
197			var $img    = new Image();
198							
199			$img.src    = src;
200					
201			var c_w		= this.elWidth,
202				c_h		= this.$el.height(),
203				r_w		= c_h / c_w,
204				
205				i_w		= $img.width,
206				i_h		= $img.height,
207				r_i		= i_h / i_w,
208				new_w, new_h, new_left, new_top;
209					
210			if( r_w > r_i ) {
211				
212				new_h	= c_h;
213				new_w	= c_h / r_i;
214			
215			}
216			else {
217			
218				new_h	= c_w * r_i;
219				new_w	= c_w;
220			
221			}
222					
223			return {
224				width	: new_w,
225				height	: new_h,
226				left	: ( c_w - new_w ) / 2,
227				top		: ( c_h - new_h ) / 2
228			};
229		
230		},
231		_initThumbs			: function() {
232		
233			// Устанавливаем свойство max-width элемента слайдера
234			// Также устанавливаем ширину каждого слайда по формуле 100% / на общее количество элементов
235			this.$sliderElems.css({
236				'max-width' : this.options.thumbMaxWidth + 'px',
237				'width'		: 100 / this.itemsCount + '%'
238			});
239			
240			// Устанавливаем свойство max-width слайда и выводим его
241			this.$sliderthumbs.css( 'max-width', this.options.thumbMaxWidth * this.itemsCount + 'px' ).show();
242			
243		},
244		_startSlideshow		: function() {
245		
246			var _self	= this;
247			
248			this.slideshow	= setTimeout( function() {
249				
250				var pos;
251				
252				( _self.current === _self.itemsCount - 1 ) ? pos = 0 : pos = _self.current + 1;
253				
254				_self._slideTo( pos );
255				
256				if( _self.options.autoplay ) {
257				
258					_self._startSlideshow();
259				
260				}
261			
262			}, this.options.slideshow_interval);
263		
264		},
265		// Выводим слайд для нажатой миниатюры
266		_slideTo			: function( pos ) {
267			
268			// выходим, если нажат тот же элемент или он анаимируется в данный момент
269			if( pos === this.current || this.isAnimating )
270				return false;
271			
272			this.isAnimating	= true;
273			
274			var $currentSlide	= this.$imgItems.eq( this.current ),
275				$nextSlide		= this.$imgItems.eq( pos ),
276				_self			= this,
277				
278				preCSS			= {zIndex	: 10},
279				animCSS			= {opacity	: 1};
280			
281			// Новый слайд будет выскальзывать слева или справа
282			if( this.options.animation === 'sides' ) {
283				
284				preCSS.left		= ( pos > this.current ) ? -1 * this.elWidth : this.elWidth;
285				animCSS.left	= 0;
286			
287			}	
288			
289			// Анимация заголовков
290			$nextSlide.find('div.ei-title > h2')
291					  .css( 'margin-right', 50 + 'px' )
292					  .stop()
293					  .delay( this.options.speed * this.options.titlesFactor )
294					  .animate({ marginRight : 0 + 'px', opacity : 1 }, this.options.titlespeed, this.options.titleeasing )
295					  .end()
296					  .find('div.ei-title > h3')
297					  .css( 'margin-right', -50 + 'px' )
298					  .stop()
299					  .delay( this.options.speed * this.options.titlesFactor )
300					  .animate({ marginRight : 0 + 'px', opacity : 1 }, this.options.titlespeed, this.options.titleeasing )
301			
302			$.when(
303				
304				// Убираем текущии заголвоки
305				$currentSlide.css( 'z-index' , 1 ).find('div.ei-title > *').stop().fadeOut( this.options.speed / 2, function() {
306					// сбрасываем стили
307					$(this).show().css( 'opacity', 0 );	
308				}),
309				
310				// Анимация вывода следующего слайдаы
311				$nextSlide.css( preCSS ).stop().animate( animCSS, this.options.speed, this.options.easing ),
312				
313				// Перемещаем индикатор в нвое положение
314				this.$sliderElem.stop().animate({
315					left	: this.$thumbs.eq( pos ).position().left
316				}, this.options.speed )
317				
318			).done( function() {
319				
320				// Сбрасываем значения
321				$currentSlide.css( 'opacity' , 0 ).find('div.ei-title > *').css( 'opacity', 0 );
322					_self.current	= pos;
323					_self.isAnimating		= false;
324				
325				});
326				
327		},
328		_initEvents			: function() {
329			
330			var _self	= this;
331			
332			// Изменение размеров окна
333			$(window).on( 'smartresize.eislideshow', function( event ) {
334				
335				// Изменяем размеры изображений
336				_self._setImagesSize();
337			
338				// Сбрасываем положение миниатюр
339				_self.$sliderElem.css( 'left', _self.$thumbs.eq( _self.current ).position().left );
340			
341			});
342			
343			// Нажатие на миниатюре
344			this.$thumbs.on( 'click.eislideshow', function( event ) {
345				
346				if( _self.options.autoplay ) {
347				
348					clearTimeout( _self.slideshow );
349					_self.options.autoplay	= false;
350				
351				}
352				
353				var $thumb	= $(this),
354					idx		= $thumb.index() - 1;
355					
356				_self._slideTo( idx );
357				
358				return false;
359			
360			});
361			
362		}
363	};
364	
365	var logError 				= function( message ) {
366		
367		if ( this.console ) {
368			
369			console.error( message );
370			
371		}
372		
373	};
374	
375	$.fn.eislideshow			= function( options ) {
376	
377		if ( typeof options === 'string' ) {
378		
379			var args = Array.prototype.slice.call( arguments, 1 );
380
381			this.each(function() {
382			
383				var instance = $.data( this, 'eislideshow' );
384				
385				if ( !instance ) {
386					logError( "cannot call methods on eislideshow prior to initialization; " +
387					"attempted to call method '" + options + "'" );
388					return;
389				}
390				
391				if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) {
392					logError( "no such method '" + options + "' for eislideshow instance" );
393					return;
394				}
395				
396				instance[ options ].apply( instance, args );
397			
398			});
399		
400		} 
401		else {
402		
403			this.each(function() {
404			
405				var instance = $.data( this, 'eislideshow' );
406				if ( !instance ) {
407					$.data( this, 'eislideshow', new $.Slideshow( options, this ) );
408				}
409			
410			});
411		
412		}
413		
414		return this;
415		
416	};
417	
418})( window, jQuery );

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.