Skip to content Skip to sidebar Skip to footer

Show/hide Span On The Same Spot

I am using jQuery to show or hide a span. But I want the
to appear in the same place as the link I click. The current code actually shows the
tags on the le

Solution 1:

this can be your HTML part:

<ahref="#"class="show_hide"style="position: relative;">Japan</a><spanclass="slidingDiv"style="position: absolute; left: 0;"><imgsrc="02-1 ImageFiles/01 Japan.JPG"style="width: 235px; height: 245px;" /><ahref="#"class="show_hide_close">Close</a></span>
is made up of islands, regions, prefectures (government districts), cities, and surrounding communities. The main island, Honshu, has thirty-four prefectures making up five regions. The
<aclass="show_hide"href="#"style="position: relative;">T&#197;hoku Region</a><spanclass="slidingDiv"style="position: absolute; left: 0;"><imgsrc="02-1 ImageFiles/02 TohokuRegion.JPG"style="width: 217px; height: 236px;" /><ahref="#"class="show_hide_close">Close</a></span>

and this can be your script part:

<scripttype="text/javascript">
    $(document).ready(function () {
    $(".slidingDiv").hide();
    $(".show_hide").show();

    $('.show_hide').click(function () {
        var el = $(this);
        var slidingDiv = el.find("span.slidingDiv");
        if (slidingDiv.length > 0) {
            slidingDiv.slideToggle(function () { el.after(slidingDiv); });
        }
        else {
            slidingDiv = el.next("span.slidingDiv");
            el.append(slidingDiv);
            slidingDiv.slideToggle();
        }
        returnfalse;
    });
    $('.show_hide_close').click(function () {
        $(this).parent().parent("a.show_hide").click();
        returnfalse;
    });
});

Explanation:

  • the script will append the span to the anchor on click and will move it back to its original place on closing. the reason is that you cannot wrap a block (here is the span) in an anchor tag in the html code, so we will do it at run-time. and we should wrap it because we need to show the span below the anchor tag.

  • span containing the img and close button should have absolute position

  • anchor which will be clicked should have relative position so browser can calculate the position of the span from the parent anchor, so it will be now below the link

  • I generalized anchor and span classes, so you can use it with only one script block

  • different class has been assigned to the close button, so clicking it will click the parent anchor

Solution 2:

Remove the div and Set the span to display: block

<ahref="#"class="show_hide">Japan</a><ahref="#"class="show_hide">Close</a><spanclass="slidingDiv"><imgsrc="02-1 ImageFiles/01 Japan.JPG"style="width:235px; height:245px;" /></span>

span
{
   display: block;
}​

Check Fiddle

Post a Comment for "Show/hide Span On The Same Spot"