tags:

views:

35

answers:

2

Hi. I am creating a portfolio page for m personal site. I have a slider with approx 20 anchors that link to projects I have worked on, each one contains a client logo that when clicked should load some html content then fade that content into a container div on the same page.

I have been advised to use the JQuery method load() which seems straight forward. The question I have is do I have to repeat the following code for each of the 20 anchors as the url is different for each one or is there a more efficient way?

$('a#project1').click(function() {
   $('#work').load('ajax/project1.html');
}

Also would I have to use the unload() method first to ensure the div I am loading into is empty? Many thanks in advance.

+4  A: 

If you just give the anchors an href and a class like this:

<a class="project" href="ajax/project1.html">Project 1</a>
<a class="project" href="ajax/project2.html">Project 2</a>

You can use jQuery like this for all of them:

$('a.project').click(function() {
  $('#work').load(this.href);
}

Solution 2: If your links are in a container, you could change the selector slightly and have less repetition, like this:

<div class="projects">
  <a href="ajax/project1.html">Project 1</a>
  <a href="ajax/project2.html">Project 2</a>
</div>

The you'd use this:

$('.projects a').click(function() {
  $('#work').load(this.href);
}

The benefit of both these approaches is that with javascript disabled, they degrade somewhat gracefully (depending on how your content looks) and the user can still see the content by clicking the link.

Nick Craver
A: 

To answer your second question, no, you don't have to use unload. As the documentation for load explains, it fetches the URL and puts the resulting HTML into the container specified - as if you did a .innerHTML on your work div.

Under the latest jQuery, try:

$('#slider-id').delegate('a', 'click', function() {
    $('#work').load(this.href);
});

If using jQuery 1.3, try:

// All anchors you want to be activated need to have the class workLink
$('a.workLink').live('click', functiON() {
    $('#work').load(this.href);
});
justkt
@justkt- Isn't there some sort of overhead for `delegate` and `live` as opposed to a regular `bind` if the "liveness" of the former functions isn't needed?
Jeremy
Here's some profiling done to answer that question: http://www.ravelrumba.com/blog/event-delegation-jquery-performance/
justkt