user1736794
user1736794

Reputation: 265

jquery show hide div's with a href tag

I have some jquery which reveals and hides new div's based on which button is pressed. Rather than buttons i would like to insert my own text/image and have them work in the same way, revealing and hiding the new windows.

Here is the jquery:

<script>
    $(document).ready(function(){

        $(".buttons").click(function () {
        var divname= this.value;
          $("#"+divname).show("slow").siblings().hide("slow");
        });

      });
</script> 

Here is the code for one of the buttons which i would like changed to a a href tag.

<input type="button" id="button1" class="buttons" value="div1"></input>

Any help will be greatly appreciated. Thanks. Pia

Upvotes: 0

Views: 8114

Answers (1)

doublesharp
doublesharp

Reputation: 27599

You can use the jQuery data() method - http://api.jquery.com/data/ - to store arbitrary data on the anchor element (the div ID) and then use that value to show the proper div:

<div id="div1">div one</div>
<div id="div2">div two</div>
<a href="#" class="abuttons" data-divid="div1">link</a>

<script>
$(document).ready(function(){
    $(".abuttons").click(function () {
        var idname= $(this).data('divid');
        $("#"+idname).show("slow").siblings().hide("slow");
    });
});
</script>

If you want to show two div's using a class name instead of an ID, store the class name on the achor tag, set the same class on each of the divs you want to show, and reference it in jQuery using a . instead of a #

<div id="div1" class="divclass">div one</div>
<div id="div2" class="divclass">div two</div>

<a href="#" class="abuttons" data-divclass="divclass">link</a>

<script>
$(document).ready(function(){
    $(".abuttons").click(function () {
        var classname= $(this).data('divclass');
        $("."+classname).show("slow").siblings().hide("slow");
    });
});
</script> 

Upvotes: 5

Related Questions