views:

61

answers:

2
+1  Q: 

JQuery load help

Hi. I am trying to use load() to place some html into a div on a page. I have a bunch of links like this:

    <div id="slideshow">
        <div id="slides">
        <div class="projects">
            <a href="work/mobus.html" title="Mobus Fabrics Website">
                <img src="images/work/mobus.jpg" alt="Mobus Fabrics Website" width="280" height="100" />
            </a>

            <a href="work/eglin.html" title="Eglin Ltd Website">
                <img src="images/work/eglin.jpg" alt="Eglin Ltd Website" width="280" height="100" />
            </a>

            <a href="work/first-brands.html" title="First Brands Website">
                <img src="images/work/first-brands.jpg" alt="First Brands Website" width="280" height="100" />
            </a>
        </div>

        <a id="prev"></a>
        <a id="next"></a>
    </div>

and my jquery code looks like this:

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

The problem is when clicked the html is placed in the #work div the html is loaded in another page. Please can anyone help?

+6  A: 

You need to prevent the default action to stop the href being loaded:

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

    event.preventDefault();
});

You may also see people achieving the same by doing:

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

    return false;
});

However, this method will stop the event bubbling any further, as well as preventing the default action. If you've got any delegate or live methods listening for the same event further up the DOM tree, doing return false will stop these handlers being called.

Edit: For the callback function:

$('.projects a').click(function(event) {
    $('#work').load(this.href, function (text) {
        alert("This loaded: " + text);
    });

    event.preventDefault();
});
Matt
@Matt that seems to disable the whole button it doesn't load the href but it also doesn't place the html in #work
mtwallet
It will do. Check that there is an element with an id of work. Try adding a callback function to ensure the request is completing: add a function as a second parameter and add a simple alert or something. See my edit for an example. Add an alert inside the click event to prove the handler is being called.
Matt
@Matt I had another id on the page with the same name. Thanks a lot for the help I appreciate it!
mtwallet
+1  A: 

You have to prevent the event from chaining.. the browser will eventually follow the link.

See preventDefault

Mike Gleason jr Couturier