Banny
Banny

Reputation: 841

Creating a javascript function to make a button click

I want to make it so that when a track completes playing it automatically calls a javascript function which clicks the next track button so that the playlist continues to play. So far i have:

function next() {
    $("#nextTrack").click();
}

But that doesn't seem to do anything when it is called, anyone know where i am going wrong?

Upvotes: 0

Views: 145

Answers (1)

Ian
Ian

Reputation: 50905

The way to trigger the click event on the DOM element itself is with:

$("#nextTrack")[0].click();

This gets the first (only) DOM element matched (removes it from the jQuery wrapper) and calls the native click method.

The only reasoning I can provide for this is because trigger doesn't (or hasn't, in past versions) attempted to call the native method. I swear in the most recent version, I can use .trigger("click") (same as .click()) and it will effectively click the element...executing native any click handlers and jQuery handlers as well.

trigger is tricky because jQuery stores any event handlers bound with jQuery.on, jQuery.bind, etc. in a special place. When the native event is fired, or .trigger("event_name") is used, all those special handlers are executed. But for some reason, the native event isn't always triggered (as you seem to have found out). I'm not sure if it's because of the version of jQuery or the event type.

UPDATE:

The reason this is happening is because jQuery treats <a> specially when using .trigger("event_name"), specifically for the click event.

After blabbering with the stuff above, I decided to look into the jQuery source code for trigger. In the end, the native DOM method is called, with elem[ type ]();. But it only gets to this point under certain conditions...these are the conditions (among other nested if statements):

if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) &&
    !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {

And I'm guessing that specifically, the part !(type === "click" && jQuery.nodeName( elem, "a" )) is what prevents it in your case, because the element you're targeting is <a>, and it's the click event.

DEMO: Here's basically just something mimicking your code in a simpler fashion: http://jsfiddle.net/EjVMY/ - notice how the initial console.log on load doesn't execute (because of the trigger). But as soon as you actually click on the event, the console.log does execute. I found that replacing the <a> with a <div> changes the behavior - it logs on load.

Of course, if I had just Googled it in the first place, I would've found: trigger a click on a anchor link

Upvotes: 2

Related Questions