rossautomatica
rossautomatica

Reputation: 459

Show a child div when link clicked

I have a series of divs with links and hidden divs. When the link is clicked, I need the hidden div within the parent to be shown. For example:

<div class="track" id="track1">
<a href="#" class="notes-link">Song Notes</a>
<div class="song-notes"></div> <!-- HIDDEN DIV TO BE SHOWN WHEN LINK CLICKED -->
</div>

<div class="track" id="track2">
<a href="#" class="notes-link">Song Notes</a>
<div class="song-notes"></div> <!-- HIDDEN DIV TO BE SHOWN WHEN LINK CLICKED -->
</div>

So far, the option that I tried opened up ALL of the .song-notes divs, but I want to specify that it's only the child divs of the parent div where the link is contained that should be opened.

Upvotes: 2

Views: 846

Answers (5)

Rizwan Ahmed
Rizwan Ahmed

Reputation: 146

Add id to the hidden divs

<div class="track" id="track1">
<a href="javascript:showNotes(1);" class="notes-link">Song Notes</a>
<div class="song-notes" style="display:none" id="song1">1</div> <!-- HIDDEN DIV TO BE SHOWN WHEN LINK CLICKED -->
</div>

<div class="track" id="track2">
<a href="javascript:showNotes(2);" class="notes-link">Song Notes</a>
<div class="song-notes" style="display:none" id="song2">2</div> <!-- HIDDEN DIV TO BE SHOWN WHEN LINK CLICKED -->
</div>

Javascript Code:

    function showNotes(id){
        $('#song'+id).toggle();
    }

Demo: http://jsfiddle.net/Zz65U/

Upvotes: 1

j08691
j08691

Reputation: 207901

I like using .toggle() here.

$('a.notes-link').click(function (){
    $(this).next('.song-notes').toggle();
});

jsFiddle example

Upvotes: 3

$(function () {
    $('div.track a.notes-link').click(function (e) {
        e.preventDefault();
        $(this).next().show(); //$(this).next().toggle();--> to show hide
    });
});

.next()

.toggle()

Upvotes: 1

Amit Joki
Amit Joki

Reputation: 59232

You can do this:

$(function () {
    $('.notes-link').click(function (e) {
        e.preventDefault();
        $(this).next().show();
    });
});

Demo

Upvotes: 1

Alessandro Minoccheri
Alessandro Minoccheri

Reputation: 35973

try this

$(document).ready(function(){
    $('.notes-link').click(function(ev){
       ev.preventDefault();
       $(this).closest('.track').find('.song-notes').show();
    });
});

DEMO

Upvotes: 2

Related Questions