Thomas Le
Thomas Le

Reputation: 305

Trigger click event in a loop

I am writing a bookmarklet to gather information from my Indiegala bundles I bought. Instead of gifting the whole bundle I am gifting onesies and twosies at a time so having the individual gift urls makes it easier.

Before they had it so the key was there and I could just gather it with a simple selector, now they have a little image you have to click on to get the gift url for each steam/desura game.

I would like to, in a loop, click all of these gift images to get the gift url to appear and then loop through and get those gift urls. I wrote this:

var gifts = $('#icon-gift img');
for(var j=0; j < gifts.length-1; j++){
  gifts[j].click();
}

to loop through all the images and trigger the click so the gift url will appear. I know it goes through each of the images because it logs to the console so I know it isn't getting stuck but for some reason it ONLY clicks the first image available. After you click an image (thankfully) it is clicked forever and when I refresh it only has the gift url then if I run the loop again it does the very next one (but that defeats the purpose of doing it in a script).

I have tried adding a delay(500) and even delay(1500) appended to the click() but that doesn't seem to change anything.

My question is: does anyone know why this would happen and is there any advice on how to fix or get around this?

More thoughts and info

I think it has something to do with asynchronicity. It's like the rest of the loop does everything else except for the other click event. I tried: var gifts = $('#icon-gift img');

$.each(gifts, function(i, val){
  setTimeout(function(){
    val.click();
    val.remove();
  }, 1000);
});

and it still only does the first one and removes all the other images. If i manually go through gifts[0].remove(); then gifts[0].click(); it does the very next one. This is exactly what I thought the .each() or a for loop would do, but it seems like it can't execute the next click with the previous one still being executed or still present.

Upvotes: 0

Views: 3839

Answers (1)

tic
tic

Reputation: 2512

No need to use for loop

$('#icon-gift img').click();

is quite enough. It will perform a click on all the passed selectors #icon-gift img -> which are all the descendant images of #icon-gift. All of them.

Otherwise you code was not working cause using gifts[j] you're actually extracting from the Array of your jQuery selectors the JS reference to the DOM HTML node element, therefore not any more a jQuery Object element. Wrapping it again in an jQuery object would work $(gifts[j]) or using the eq() selector like gifts.eq(j), but again not needed as I demonstrated above.

Upvotes: 5

Related Questions