views:

173

answers:

4

I have some markup like this:

<p><a id="1" href="#">Link 1</a></p>
<p id="1show" class="starthidden">Hi! I get shown when link 1 is clicked</p>

<p><a id="2" href="#">Link 2</a></p>
<p id="2show" class="starthidden">Hi! I get shown when link 2 is clicked</p>

<p><a id="3" href="#">Link 3</a></p>
<p id="3show" class="starthidden">Hi! I get shown when link 3 is clicked</p>

And some javascript like this:

$(document).ready(function(){

    $("#maincontent a").click(function () {
     var id = '#' + $(this).attr("id");
     var show = id + 'show';

     $("id").click(function () {
      $("show").slideToggle("slow");
      return false;
     });

     return false;
    });

});

Now, id and show are both what I'd expect at runtime, but the next line doesn't work. I guess that it's the $("id") bit - though changing this to $(id) doesn't work either.

How do I fix this?

+2  A: 

Variables inside double strings aren't parsed as they are in PHP, so you must do $(show). Also, the inner click() binding is unnecessary - you can just run the slideToggle():

$(document).ready(function(){

    $("#maincontent a").click(function () {
        var id = '#' + $(this).attr("id");
        var show = id + 'show';

        $(show).slideToggle("slow");

        return false;
    });

});
TenebrousX
You beat me to it with a better analysis TenebrousX
Cyril Gupta
Thanks so much! jQuery seems pretty much awesome!
Rich Bradshaw
A: 

Well, I don't see any element with ID maincontent in the listed code. Anyhow. I see this line in your code

$("id").click

Why the double quotes if you want to access a variable?

Cyril Gupta
+2  A: 

You don't need the ids! Try this:

$(function(){
    $("a").click(function(){
        $(this).parents("p").slice(0,1).next("p").slideToggle("slow");
    });
});
svinto
+4  A: 

First off, numerical ID's are not valid HTML. ID attributes must start with a-z. I recommend changing your HTML like this:

<p><a href="#msg1">Link 1</a></p>
<p id="msg1" class="starthidden">Hi! I get shown when link 1 is clicked</p>

<p><a href="#msg2">Link 2</a></p>
<p id="msg2" class="starthidden">Hi! I get shown when link 2 is clicked</p>

<p><a href="#msg3">Link 3</a></p>
<p id="msg3" class="starthidden">Hi! I get shown when link 3 is clicked</p>

Which is both valid and clearer. On devices that don't have javascript/css it will additionally move focus to the right place.

You can then simply pick up the href off the link when the click happens:

$(document).ready(function(){

    $("#maincontent a").click(function () {

        var id = $( this ).attr( 'href' );
        $( id ).slideToggle( 'slow' );
        return false;

    });

});
Borgar
That's much neater. Not sure why I went for the id route, this makes more sense!
Rich Bradshaw