jmp jmp - 1 year ago 118
Javascript Question

Simulate user click on anchor tag with jQuery from console

I'm trying to simulate a user click on a button (from the console) and I can't get anything to work.

First, visit (using Chrome). Next, inspect the page elements and toggle the device so that Chrome's mobile device simulator opens (we need the mobile site).

I want to click on the hamburger menu (three stacked lines) using jQuery but nothing I enter into the console will do that (the solution must work from the console). The element looks like this:

<a href="javascript:;" title="More ..." class="nav icon More">Navigate</a>

Initially I thought that the
that was causing the problem (I realize that normally it shouldn't but I was grasping at straws), but after doing some testing it doesn't seem that like that's the case.

I have tried the following:

$('a.nav.icon.More').trigger() // returns error

I have also tried clicking on the parents element(s) in case the event listener was attached to one of those, but to no avail. Can anyone point me in the right direction?

Answer Source

This is a weird problem indeed. All of the usual ways to click don't work, as you've noticed. I'm surprised at the "answers" posted here since it's clear from just trying them that none of them work for this site you've linked.

Looking at the source code, it appears the site's JS does some strange things with event binding in a non-traditional way (for example, the show/hide menu event is bound to hamburger on an ns.CLICK event instead of a traditional click event). There is also the strangeness of my browser's forward and back buttons changing whenever I click and re-click the menu manually, making me think something is strange with the way routing and history is implemented.

So, you're not going crazy:) I can't think of an easy way to trigger the click on the site, but from the JS we can also see that the click event is equivalent to toggling the hidden class from ExtendedNav. So if you want an equivalent of the action the click would do, you can call $('.ExtendedNav').toggleClass('hidden').

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download