Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Seonghoon Cha
PLUS
Seonghoon Cha
Courses Plus Student 5,369 Points

Sometimes click event does not fire in drop down

this is jsp

<ul class="nav navbar-nav  float-xs-right hidden-sm-down">
                <li class="dropdown dropdown-user nav-item">
                    <sec:authorize access="isAnonymous()">
                        <a href="<spring:url value="/login"/>" class="nav-link"><span class="user-name"><spring:message code="button.login"/></span></a>
                    </sec:authorize>
                    <sec:authorize access="isAuthenticated()">
                        <a href="javascript:void 0;" data-toggle="dropdown" class="dropdown-toggle nav-link dropdown-user-link">
                         <span class="user-name"><sec:authentication property="principal.userNm"/></span>
                        </a>
                        <div class="dropdown-menu dropdown-menu-right">
                        <a href="<spring:url value="/user/passwordChange"/>" class="dropdown-item"><i class="ft-message-square"></i> <spring:message code="button.change-password"/></a>
                            <div class="dropdown-divider"></div>
                            <form class="login-form">
                                <sec:csrfInput/>
                                <a href="javascript:void 0;" class="dropdown-item logout"><i class="ft-power"></i> <spring:message code="button.logout"/></a>
                            </form>
                        </div>
                    </sec:authorize>
                </li>
            </ul>

and this is JS source for click event

$('.logout').off().on('mousedown', function (event) {
      event.preventDefault();
      var logoutForm = $(this).parent('form.login-form');
      logoutForm.attr('action', $.appendContextPath('/logout'));
      logoutForm.attr('method', 'post');
      logoutForm.submit();
    });

it is working, but sometimes it does not work.... I don't know why.. I need your help.. thank you

Can you format your code so it can be read?

1 Answer

The reason is that sometimes you click on the HTML inside the .logout this will trigger the event but the preventDefault will stop it bubbling up and the code will not work.

You need to check whether you are at the <a> and only process the code if you are. THEN you can do preventDefault.