Help me reduce code repetition in a simple jQuery function

I have built a carousel using jQuery loop plugin. I have 4 links that go to the respective slides. Right now, I have a piece of code for each link. I am trying to create a single multipurpose function.

   $('#features-slide0').click(function() {  
       $('#features-slides').cycle(0);  
       return false;  
   });

   $('#features-slide1').click(function() {  
       $('#features-slides').cycle(1);  
       return false;  
   });

   $('#features-slide2').click(function() {  
       $('#features-slides').cycle(2);  
       return false;  
   });

   $('#features-slide3').click(function() {  
       $('#features-slides').cycle(3);  
       return false;  
   });

      

I have a rel value for each link that carries a slide number. How can I use this to create a single block of code that takes care of the link transition?

<a id="features-slide0" href="" rel="0">Lorum ipsum dolor sit amet lorum ipsum dolor sit amet.</a>
<a id="features-slide1" href="" rel="1">Lorum ipsum dolor sit amet lorum ipsum dolor sit amet.</a>
<a id="features-slide2" href="" rel="2">Lorum ipsum dolor sit amet lorum ipsum dolor sit amet.</a>
<a id="features-slide3" href="" rel="3">Lorum ipsum dolor sit amet lorum ipsum dolor sit amet.</a>

      

+2


a source to share


4 answers


Guessing in your HTML:

// assumes you have links within a features div
$('#features a').click(function() {  
    $('#features-slides').cycle( // call `cycle` with the rel# of clicked item
      parseInt(                  // turn the attribute value into a number
          $(this).attr('rel')    // retrieve the attribute value for clicked item
      )
    );
    return false;  // don't follow the link
});

      



parseInt()

- built-in JS function. It just turns the string into a number.

+2


a source


jQuery.index()

can be used to grab the index of an item as opposed to the parent item.



$('a[id^=features-slide]').click(function() {  
    $('#features-slides').cycle($(this).index());  
    return false;  
});

      

+3


a source


for (var i = 4; i--;) {
  $('#features-slide'+i).click(function() {  
    $('#features-slides').cycle(i);  
    return false;  
  });
}

      

0


a source


abstraction. create a method with constants and pass the variables. thus have functions like this ...

function cycleFunction(num)
{
 $('#features-slide'+num).cycle(num);
 return false;  
}

      

Then you can call it from any click event

$('#features-slide1').click(function() {  
       return $('#features-slide1').cycleFunction(1);  
   });

      

This way you can only change the function in one place and it will change it for everyone who calls it. Aaaand you can add more "slides" that use it too. You will still have to repeat the code to attach it to the click events, but I think it's good to have this assignment explicit to make it easier to read what you are trying to do :)

0


a source







All Articles