probablybest
probablybest

Reputation: 1445

Stop event.preventDefault being applied to all links

I have a CSS menu hover that isn't working on iPad. Looking around I found this answer on Stack Overflow. To trigger the hover I have set up an event.preventDefault on the top level links which is working great. However this being applied to all links under the menu which means you cant navigate around the website.

I have created a jsFiddle.

How can I make it so that anything with a class .menu-item-has-children the event is prevented but for any other <a></a> under that class is works.

Unfortunately/annoyingly its not possible to edit the HTML markup

Here is my code:

HTML

<nav id="top-menu">
<ul>
    <li class="menu-item-has-children"><a>Link 1</a>
        <ul>
            <li><a href="http://www.google.co.uk">Google</a></li>
            <li class="menu-item-has-children"><a href="http://www.google.co.uk">Google</a>
                <ul>
                   <li><a href="#">Google 1</a></li>
                   <li><a href="#">Google 1</a></li>
                   <li><a href="#">Google 1</a></li>
                   <li><a href="#">Google 1</a></li>
                </ul>
            </li>
            <li><a href="#">Google</a></li>
            <li><a href="#">Google</a></li>
        </ul>
    </li>
    <li class="menu-item-has-children"><a>Link 2</a>
       <ul>
            <li><a href="#">Google</a></li>
            <li><a href="#">Google</a></li>
            <li><a href="#">Google</a></li>
            <li><a href="#">Google</a></li>
        </ul>
    </li>
    <li class="menu-item-has-children"><a>Link 3</a>
        <ul>
            <li><a href="#">Google</a></li>
            <li><a href="#">Google</a></li>
            <li><a href="#">Google</a></li>
            <li><a href="#">Google</a></li>
        </ul>
    </li>
    <li class="menu-item-has-children"><a>Link 4</a>
        <ul>
            <li><a href="#">Google</a></li>
            <li><a href="#">Google</a></li>
            <li><a href="#">Google</a></li>
            <li><a href="#">Google</a></li>
        </ul>
    </li>
</ul>

jQuery:

$("#top-menu .menu-item-has-children a").click(function( event ) {
    event.preventDefault();
    console.log('clicked');
});

Upvotes: 0

Views: 168

Answers (1)

Ted
Ted

Reputation: 14927

Add a > (CSS Direct Descendant Selector):

$("#top-menu .menu-item-has-children > a").click(function( event ) {
    event.preventDefault();
    console.log('clicked');
});

That selects only<a/> tags that are a direct descendant of menu-item-has-children.

So for example, in this code block, it selects the 'Link 2' anchor, but not any 'Google' anchor:

<li class="menu-item-has-children"><a>Link 2</a>
   <ul>
        <li><a href="#">Google</a></li>
        <li><a href="#">Google</a></li>
        <li><a href="#">Google</a></li>
        <li><a href="#">Google</a></li>
    </ul>
</li>

Upvotes: 1

Related Questions