RysQ
RysQ

Reputation: 348

accordion menu - e.preventDefault. How to keep standard action of <a href="">

I spent more than hour reading api.jquery.com, and the same time trying to do it by myself.

And still I dont know how to solve the problem in the right way.

I've this accordion script:

$(document).ready(function(){    
    $(".menu-list > li > a").on("click", function(e){    
        if($(this).parent().has("ul")) {
            e.preventDefault();
        }    
        if(!$(this).hasClass("open")) {
            $(".menu-list li ul").slideUp(350);
            $(".menu-list li a").removeClass("open");          
            $(this).next("ul").slideDown(350);
            $(this).addClass("open");
        }        
        else if($(this).hasClass("open")) {    
            $(this).removeClass("open");
            $(this).next("ul").slideUp(350);
        }
    });
});

And menu looks like this:

<ul class="menu-list">
    <li><a href="panel.php" class="panel">Panel</a></li>
    <li><a href="doesn't matter" class="articles">Articles</a>
        <ul>
            <li><a href="somepage.php">Some page</a></li>
            <li><a href="somepage2.php">Some page 2</a></li>
            <li><a href="somepage3.php">Some page 3</a></li>
        </ul>
    </li>
    <li>.........

ofcourse becouse of e.preventDefault(); clicked links will not take the browser to assigned page. Clicked element will expand <ul> contained in <li>. Thats good.

But anyway for some links I would like to keep standard action of <a> (for exaple <li><a href="panel.php" class="panel">Panel</a></li>) so they can take me to the page in href

The problem is how to do this while retaining the correct working of accordion for rest of elements.

The best thing I came up with so far is removeing e.preventDefault(); and insert # into links I'd like to work as trigger. But is that correct way?

(Sorry form my english if there are any errors)

Upvotes: 1

Views: 670

Answers (1)

andreivictor
andreivictor

Reputation: 8461

You can add a custom class to your elements that you want to act as a "real" link.

 <a href="file1.php" class="real-link">Link1</a>
 <a href="file2.php" class="real-link">Link2</a>

Then add this line to your click event handler:

 if($(this).hasClass('real-link')) return true;

Upvotes: 3

Related Questions