Yahreen
Yahreen

Reputation: 1669

Function Syntax, Passing Variables

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/

Upvotes: 0

Views: 140

Answers (2)

thecodeparadox
thecodeparadox

Reputation: 87073

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

Upvotes: 1

SLaks
SLaks

Reputation: 887807

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.

Upvotes: 0

Related Questions