views:

189

answers:

1

The function below is called upon page ready, and is designed to mimic clicks through various anchor links, and to trigger those anchors' bound methods so as to reproduce the same DOM that would be configured through manually clicking the same links.

function useAnchor() {
    var uri = document.location.toString();
    if (uri.match('#')) {
        var anchor = '#' + uri.split('#')[1];
        $('.links a[href="/' + anchor.split('/')[0] + '/"]').click();
        $('.links a[href="/' + anchor.split('/')[0] + '/' + anchor.split('/')[1] + '/"]').click();
    }
}

Of the two event triggers, the first successfully executes the bound method. However, the second event trigger's target anchor does not exist until the first event's method is complete, since it inserts the second event's target anchor into the DOM. The second trigger fails, and my only guess is this is due to not being able to find its target anchor, thus suggesting the first trigger is not fully complete at the time of the second trigger being called. I wouldn't have thought this to be the case - or is my code somehow running in multiple threads?

In short, I need someone to confirm that the triggers and their methods are executed completely synchronously, so I know if I'm bug hunting in the wrong place. Many thanks in advance.

A: 

Maybe something like this will work (I didn't try):

$('.links a[href="/' + anchor.split('/')[0] + '/"]').click(function (){
  var s = '.links a[href="/' + anchor.split('/')[0] + '/' + 
          anchor.split('/')[1] + '/"]';
  $(s).click();
}).click();
eKek0
I completely forgot I had an asynchronous ajax call running in the first trigger, hence the problem! Thanks for the response anyway.
tjbp