Rich Bradshaw
Rich Bradshaw

Reputation: 72975

Using jQuery for first time, simple problem!

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?

Upvotes: -1

Views: 252

Answers (4)

Borgar
Borgar

Reputation: 38652

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;

    });

});

Upvotes: 4

Svante Svenson
Svante Svenson

Reputation: 12488

You don't need the ids! Try this:

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

Upvotes: 2

Cyril Gupta
Cyril Gupta

Reputation: 13723

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?

Upvotes: 0

clawr
clawr

Reputation: 7895

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;
    });

});

Upvotes: 2

Related Questions