Zan
Zan

Reputation: 43

jQuery show image on hover, detect some part of element ID

I want to create a image previev on link hover that is between <a> and </a> tags. Here is my code:

<li id="pic39">
    <span class="pr2"></span>
    <a id="pic39" href="http://shrani.slo-devs.com/index.php?p=6vxK53pk" target="_blank">Sandra</a>
    <span class="edit" onclick="location.href='index.php?e=39'"></span>
    <span class="delete" onclick="deletePIC(39)"></span>
    <i class="infoSlike">(0 ogledov | 11.03.2013 / 21:59:31)</i>
    <div id="imgPrv">
        <span id="imgPrv39">
            <img src="http://www.shrani.slo-devs.com/upl/CENSURE.jpeg" />
        </span>
    </div>
</li>

I want jQuery to detect the rest part of a tag id (so, number 39) and show span that includes number 39 (span with id imgPrv39).

Upvotes: 1

Views: 1046

Answers (2)

Ram
Ram

Reputation: 144699

$('li a').hover(function(){
   // You can replace the `pic` with an empty string
   var id = this.id.replace('pic', '');
   $('#imgPrv' + id).toggle();
})

Note that IDs must be unique, you have several elements with the same IDs, your markup is invalid, you should use classes instead.

You can also use siblings method:

$('li a').hover(function(){
   $(this).siblings('div').find('span').toggle();
})

Upvotes: 1

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114417

You don't need to do it this way. You can use relative selectors and eliminate all this ID business.

This assumes there is only one A and one SPAN in your LI. You can use class names instead if you want to be more specific.

$("li a").hover(
  function () {
    $(this).find('span').show();
  },
  function () {
     $(this).find('span').hide();
  }
);

Upvotes: 0

Related Questions