apply a show on hover to a repeating div that changes name

Ok I have a div that I increment the name by one on every loop. There could be an infinate number of divs as they are part of a news loop

   <?php $i=1; do {?>
 <div id="linkdiv<?php echo $i;?>">
     <div id="divTwo<?php echo $i;?>" style="display: none;"><a href="#">Edit</a></div>
   </div>
  <?php } while($row= mysql_fetch_assoc($rs_query)); ?>

both divs have a statement to increment the number by one every loop. Works fine! Now I have a function in the header which when you hover over linkdiv it displays divTwo.

 <script type="text/javascript">
$(function() {
$('#linkdiv').hover(function() { 
    $('#divTwo').show(); 
}, function() { 
    $('#divTwo').hide(); 
});
});
</script>

It is possible to adapt this function to work with what I have got? I have tried moving the function inside my loop but that doesnt seem to work

Answers


You can use starts with selector. Try the following:

Selects elements that have the specified attribute with a value beginning exactly with a given string.

$('div[id^=linkdiv]').hover(function() { 
    $(this).find('div').show(); 
}, function() { 
    $(this).find('div').hide(); 
});

ids need to be explicitly different within a page...for same use class attribute.


Not tested

 <script type="text/javascript">
   $(function() {
      $('div[id^="linkdiv"]').hover(function() { 
         $(this).next().show(); 
       }, function() { 
         $('this').next().hide(); 
       });
    });
</script>

A better way would be to give a class to all your divs

<div class="linkdiv" id="linkdiv23">...</div>

Now you don't need to use any trickery -

$('div.linkdiv').hover(function() { 
    $(this).find('div').show(); 
}, function() { 
    $(this).find('div').hide(); 
});

made changes to markup, more simple and more options with jquery, you can target all with .linkdiv or specific with .linkdiv-X, same applies to .divTwo

  <?php $i=1; do {?>
 <div class="linkdiv linkdiv-<?php echo $i;?>">
     <div class="divTwo divTwo-<?php echo $i;?>" style="display: none;"><a href="#">Edit</a></div>
   </div>
  <?php } while($row= mysql_fetch_assoc($rs_query)); ?>

this should generate something like

 <div class="linkdiv linkdiv-X">
     <div class="divTwo divTwo-X" style="display: none;"><a href="#">Edit</a></div>
   </div>

and jquery for that

$(".linkdiv").hover(function(){
 $(this).find(".divTwo").show();
},function(){
 $(this).find(".divTwo").hide();
});

Need Your Help

iPhone OS 3 SDK?

objective-c cocoa-touch iphone-sdk-3.0 ios4

How can I install the iPhone OS 3 SDK beside the iOS 4 SDK? Is it possible?

What is the Symbol function in Chrome?

javascript google-chrome

I tried checking MDN for resources on this, but the only one I came across was this, and that doesn't mention any such functions existing.