tags:

views:

108

answers:

5

I'm using jQuery Tools (http://flowplayer.org/tools/index.html) to create tooltips, I've created a js-file that holds the following lines:

$("div#example-0").tooltip('#example-0-tooltip');
$("div#example-1").tooltip('#example-1-tooltip');
$("div#example-2").tooltip('#example-2-tooltip');
$("div#example-3").tooltip('#example-3-tooltip');

etc.

This works fine if there's a known number of example-divs, however I would like this to work with an unknown number of example-divs.

Basically I would like my jQuery to be able to read the DOM-tree and determine how many example-divs there is and somehow loop through them all and add the tooltip.

Anyone know how to do this?

+1  A: 

Give them all the same class so that you can just do

$('div.classname').tooltip(...);
BalusC
A: 

This returns element number :

$('element').size();
Nick Brooks
A: 

Put a certain class to all divs. Essential code will remain the same.

Ex:

<div id="1" class="tooltip">
</div>

<div id="2" class="tooltip">
</div>
<div id="3" class="tooltip">
</div>
<div id="4" class="tooltip">
</div>

and the code:

$("div.tooltip").tooltip('#example-0-tooltip');
Jenea
+7  A: 

Use the starts with attribute matcher and iterate. Grab the id from the current element and invoke the tooltip.

$('div[id^=example-]').each( function() {
    $(this).tooltip( '#' + $(this).attr('id') + '-tooltip' );
});

Or, if they each had the same class in addition to unique ids.

$('div.exampleClass').each( function() {
    $(this).tooltip( '#' + $(this).attr('id') + '-tooltip' );
});

Or if, as @Savageman suggests, you can get away with reusing the same named DIV for the tooltip (and use a class to mark all divs that need a tooltip).

$('div.exampleClass').tooltip('#exampleTooltip');
tvanfosson
2nd solution is good.But the tooltip plugin only needs 1 div to work. $(this).tooltip('#my-tooltip'); will do the job! Even better: $('div.exampleClass').tooltip('#my-tooltip');
Savageman
@Savageman - I'm not really familiar with the FlowPlayer tooltip plugin, nor with the user's application. I assumed that since he was using an element per tooltip that he wanted to continue to do so. If that's not then case then you can obviously simplify and do away with the each iteration and simply apply it based on class with a single named element for the argument to the tooltip.
tvanfosson
Works great! Thanks :)
timkl
@tvanfosson - Of course, I just precised this point here. I don't know wether he needs as much div, I'm just pointing out he shouldn't.
Savageman
A: 

not sure if this helps, but there's a tooltip plugin for jquery which can use the title attribute of a tag to generate a tooltip. It does it automatically, so you wouldn't have to set a statement for each, just have a title assigned to the div.

andy-score