Selector scope problem I think
I am creating a little slideshow with jQuery and I had everything working fine. At first I had the slideshow visible on document ready, but really I want it to appear only when a user clicks on an image. As soon as I put my code in a .click() event, it stopped working. If I merely comment out the .click() event the code works fine and the slideshow is visible..After debugging, it appears that the only difference is that during execution the variable slideWidth is initially set to 0 instead of the size of the image as it should. Any know what it could be?
- $(document).ready(function(){
- var currentPosition;
- var slides = $('.slide')
- var currentSlide;
- var currentImg;
- var slideWidth;
- var numberOfSlides = slides.length;
-
- $('#filter').hide();
- $('#photoWrap').hide();
- $('.imgHolder').click(function(){
- currentPosition = $('.imgHolder').index(this);
- currentSlide = $('.slide').get(currentPosition);
- currentImg = $(currentSlide).children('img');
- slideWidth = $(currentImg).width();
-
- $('#slideShow').width(slideWidth);
- // Remove scrollbar in JS
- $('#slideContainer').css('overflow', 'hidden');
- // Wrap all .slides with #slideInner div
- slides
- .wrapAll('<div id="slideInner"></div>')
- // Float left to display horizontally, readjust .slides width
- .css({
- 'float' : 'left',
- 'width' : slideWidth
- });
- // Set #slideInner width equal to total width of all slides
- $('#slideInner').css('width', (slideWidth * numberOfSlides));
- // Hide left arrow control on first load
- manageControls(currentPosition);
- $('#slideInner').css('margin-left' , slideWidth*(-currentPosition));
-
- $('#filter').show();
- $('#photoWrap').show();
- });
- // Create event listeners for .controls clicks
- $('.control')
- .bind('click', function(){
- // Determine new position
- currentPosition = ($(this).attr('id')=='rightControl') ? currentPosition+1 : currentPosition-1;
-
- currentSlide = $('.slide').get(currentPosition);
- currentImg = $(currentSlide).children('img');
- var preWidth = slideWidth;
- slideWidth = $(currentSlide).width();
- $('#slideShow').width(slideWidth);
-
- // Hide / show controls
- manageControls(currentPosition);
- // Move slideInner using margin-left
- $('#slideInner').animate({
- 'marginLeft' : slideWidth*(-currentPosition)
-
- }, 'slow');
-
-
-
-
- });
- $('#filter').click(function(){
- $(this).hide();
- $('#photoWrap').hide();
- });
- // manageControls: Hides and shows controls depending on currentPosition
- function manageControls(position){
- // Hide left arrow if position is first slide
- if(position==0){ $('#leftControl').hide() }
- else{ $('#leftControl').show() }
- // Hide right arrow if position is last slide
- if(position==numberOfSlides-1){ $('#rightControl').hide() }
- else{ $('#rightControl').show() }
- }
- });