Reputation: 601
I'm trying to auto click a button in tampermonkey, but for some reason the code isn't executing. Though, if I put the code in console and run it, it works fine.
Here it is:
$(document).ready(function() {
path = window.location.pathname;
setTimeout(autoTraderReady, 10);
$('#VehicleApplyButton').click();
});
<table id="VehicleApplyButton" class="x-btn va-apply-button x-btn-noicon x-column" cellspacing="0"><tbody class="x-btn-small x-btn-icon-small-left"><tr><td class="x-btn-tl"><i> </i></td><td class="x-btn-tc"></td><td class="x-btn-tr"><i> </i></td></tr><tr><td class="x-btn-ml"><i> </i></td><td class="x-btn-mc"><em class=" x-unselectable" unselectable="on"><button class=" x-btn-text" id="ext-gen147" type="button"> </button></em></td><td class="x-btn-mr"><i> </i></td></tr><tr><td class="x-btn-bl"><i> </i></td><td class="x-btn-bc"></td><td class="x-btn-br"><i> </i></td></tr></tbody></table>
Button does not switch dynamically, tried doing an alert when the function runs, doesn't alert me.
Upvotes: 3
Views: 5188
Reputation: 3027
For me it had to do with the particular page that I was triggering the event on.
Neither jQuery.click() nor plain elem.click() were working. I solved as a workaround creating a MouseEvent like so:
let btn = document.querySelector('.submitButton');
let clickEvent = new MouseEvent("click", {
bubbles: true,
cancelable: true,
clientX: 150,
clientY: 150
});
btn.dispatchEvent(clickEvent);
So maybe it's got to do with EventBubbling for you too.
Upvotes: 1
Reputation: 931
Given your code:
1. $(document).ready(function() {
2. path = window.location.pathname;
3. setTimeout(autoTraderReady, 10);
4. $('#VehicleApplyButton').click();
5. });
and based upon your comment below, the click on line 4 is expected to trigger an AJAX request fired from a .click
listener elsewhere in your document. If this listener exists within an external script, my suspicion is that the other listener is an not around in time to catch the click event you're triggering. That is to say, it starts listening after your click has already fired.
$(document).ready
only waits for only the DOM to load, not external scripts; try changing line 1 to $(window).on('load', function(){...});
instead.
If that fails, try adding following debugging lines:
1. $(document).ready(function() {
2. console.log( $('#VehicleApplyButton') );
3. $('#VehicleApplyButton').click(function(e){ console.log( e ) } );
4. $('#VehicleApplyButton').click();
5. });
Line 2 - confirm #VehicleApplyButton exists
Line 3 - confirm click event is propagating
Note: my first draft overlooked that jQuery
interprets .click()
as a shortcut for .trigger('click')
with no params, rather than the listener .on('click',[data],handler)
with 1-2 params. Thanks for the polite correction, @robertklep.
Upvotes: 2