0

I am trying to create multiple carousels in one page following this example.
I am creating my carousels in a foreach loop, and I assign to each carousel the names c0, c1, c2, etc. (Each carousel is a <div>)
Now, in order to run the script according to the example, I should run in on each carousel separately.
For example:

<script type="text/javascript">
    $(document).ready(function() {

        $('#c0').jsCarousel({ onthumbnailclick: function(src) { alert(src); }, autoscroll: true, masked: false, itemstodisplay: 3, orientation: 'v' });
        $('#c1').jsCarousel({ onthumbnailclick: function(src) { alert(src); }, autoscroll: false, masked: false, itemstodisplay: 5, orientation: 'h' });
        $('#c2').jsCarousel({ onthumbnailclick: function(src) { alert(src); }, autoscroll: true, masked: true, itemstodisplay: 5, orientation: 'h' });

    });       

</script>

Since my carousels are created in a foreach loop, I cannot know how many of them I will have, so I tried to call the function in a for loop:

    for (int i = 0; i < counter; i++)
    {
        string cNum = "#c" + i.ToString();%>
        <script type="text/javascript">
            $(document).ready(function() {
                $(cNum).jsCarousel({ onthumbnailclick: function(src) { alert(src); }, autoscroll: true });
            });
        </script>
   <%} %>

I checked, and the cNum values are okay, it gets the values #c0, #c1, etc. but it can't recognize it as an equivalent to '#c0' etc. that were there initially.

How can I insert dynamic carousel names into the function?

user990635
  • 3,979
  • 13
  • 45
  • 66

2 Answers2

0

Instead of doing that, just give each div a class. Like this:

<div class="someClassThatIKnowIsACarousel">

Then you don't need a loop:

$(".someClassThatIKnowIsACarousel").jsCarousel({ onthumbnailclick: function(src) { alert(src); }, autoscroll: true });
aquinas
  • 23,318
  • 5
  • 58
  • 81
0

The problem in your code is that cNum inside your dynamically generated JavaScript section isn't interpreted as an ASP variable. You could fix that with something like $('<% cNum %>') (also note the JavaScript quotes, without get you would get $(#c0), which is erroneous).

However, your approach is wrong, please avoid the best you can mixing server/client code like that.

As aquinas already pointed out, the best solution is to add a class to the divs:

HTML:

<div class="carousel">

JavaScript:

$('div.carousel').jsCarousel({ ... });
Gras Double
  • 15,901
  • 8
  • 56
  • 54