0

I am trying to make a simple function but doing something wrong. Clicking the href causes a page jump and the function fails. Fiddle: http://jsfiddle.net/XkzUK/5/

HTML:

<nav>
<ul id="site-nav">
    <li class="nav1"><a href="#recent">Recent</a></li>
    <li class="nav2"><a href="#highlights">Highlights</a></li>
    <li class="nav3"><a href="#animals">Animals</a></li>
    <li class="nav4"><a href="#cars">Cars</a></li>
</ul>
</nav>
<div id="content-listing">
    <div id="recent">
        <ul class="top-level">
        </ul>
    </div>
    <!--end recent-->
    <div id="highlights">
        <ul class="top-level">
        </ul>
    </div>
    <!--end highlights-->
    <div id="animals">
        <ul class="top-level">
        </ul>
    </div>
    <!--end animals-->
    <div id="cars">
        <ul class="top-level">
        </ul>
    </div>
    <!--end cars-->
</div>
<!--end content-listing-->

JS:

var test1;
var test2;
var test3;
var test4;

function switcher(divToShow, thisVar, otherVar, ajaxContent) {
    $("#site-nav li a").parents().removeClass("nav-active");
    $(this).addClass("nav-active");
    if(otherVar) {
        otherVar.detach();
    }

    if(typeof thisVar === 'undefined') {
        thisVar = $(divToShow + "ul.top-level").load('/echo/html/', {
            html: ajaxContent
        }, function () {
            alert("I'm new");
        });
    } else {
        thisVar.appendTo("#content-listing");
        alert("I'm old");
    }
}

//Recent
$("#site-nav .nav1").on("click", function (event) {
    switcher("#recent", "test1", "test2", "<li>1</li> <li>2</li> <li>3</li>");
    event.preventDefault();
});

//Highlights
$("#site-nav .nav2").on("click", function (event) {
    switcher("#recent", "test2", "test1", "<li>A</li> <li>B</li> <li>C</li>");
    event.preventDefault();
});​​

http://jsfiddle.net/XkzUK/5/

0

2 Answers 2

1

You have error with

otherVar.detach()

because, otherVar is just a string, so .detach() will not work, .detach() accepts jQuery object.

So correct format should be

$(otherVar).detach();

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I've fixed that problem but now my ajax won't post: jsfiddle.net/XkzUK/7
0

You're passing strings as all of those parameters.
Therefore, calling methods like detach() or appendTo() throws an error, since those methods don't exist on strings.

You need to pass jQuery objects.

1 Comment

Thanks. I've changed that but my ajax content doesn't post? jsfiddle.net/XkzUK/6

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.