As you get familiar with it, you will really appreciate how easy it is to do
string manipulation in JavaScript. I suggest spending some time learning
about the String object and the RegExp (regular expression) object. Note
that you won't find these in the jQuery docs - they are native JavaScript
features.

Don't worry if regular expressions seem complicated at first - try out some
examples and you'll get the hang of them. The Firebug console is one easy
way to try out JavaScript expressions of any sort.

For an easy case like this, you don't need regular expressions, just some
simple String and Array operations:

    $('#wrap li').click(function () {
        $( '#' + this.id.split('-')[0] ).fadeIn();
    });

Breaking that down:

this.id is the ID of the element that was clicked.

.split('-') splits that string at the - character, creating an array of two
elements:

[ 'nameN', 'link' ]

[0] selects the first element of that array, 'nameN'.

We then combine that string with a '#' (not '.') to make it an ID selector.

Also note that this.attr('id') wouldn't work: In the context of the click
handler, 'this' is a DOM element, not a jQuery object. You could do
$(this).attr('id'), but this.id is simpler.

-Mike

> From: Jason
> 
> HTML:
> 
> <ul id='list'>
> <li id='name1-link'> link </li>
> <li id='name2-link'> link </li>
> <li id='name3-link'> link </li>
> <li id='name4-link'> link </li>
> </ul>
> 
> <div id='wrap'>
> <div id='name1'> text here </div>
> <div id='name2'> text here </div>
> <div id='name3'> text here </div>
> <div id='name4'> text here </div>
> </div>
> 
> CSS:
> 
> #wrap li {display:none;}
> 
> Javascript Goal:
> 
> When a link is clicked, it's corresponding div is shown. All 
> divs are hidden by default via CSS.
> 
> Something like this:
> 
> $('#wrap li').click(function () {
>       //reference the li that was clicked and grab its ID
>       //strip out the " -link " part of the id
>       //show the div that matches this new ID });
> 
> Current Javscript:
> 
> $('#wrap li').click(function () {
>       var liName = this.attr('id');
>       $('.'+liName+-'link').fadeIn();
> });
> 
> As you can see I'm a JavaScript amateur. If 
> truncating/manipulating the ID of the link is too difficult, 
> I can switch the ID name formats
> - making it so that I would need to ADD the '-link' part, 
> which may be easier than removing? My core questions are how I would:
> 
> -select/reference the li that was clicked, and not the whole 
> array -maniuplate the ID of the id that was clicked (and store in a
> variable?)
> -use the manipulated ID to show the corresponding div (easiest part)
> 
> Thank you.
> 

Reply via email to