1

I'm trying to create a bookmarklet to open links with specific text, but I'm facing a problem with the setTimeout portion ...

javascript:(function(){
    function clickLink(link) {
        if (document.createEvent) {
            var event=document.createEvent("MouseEvents"); 
            event.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            link.dispatchEvent(event);
        } else if (link.fireEvent) {
            link.fireEvent("onclick");
        }
    } 

    l=document.links;
    for(var i=0;i<l.length;++i) {
        var lL=l[i].innerHTML.toLowerCase(); 
        if(lL.indexOf("click here")!=-1 || lL.indexOf("how")!=-1) 
             setTimeout(function() {clickLink(l[i]) }, 1000);
        }
    }; 
})();

If I try setTimeout(clickLink(l[i]), 1000);, then it works, but it runs immediately rather than waiting for the timeout!

Also want to know one more thing that clicking links this way will fire mousedown/mouseup event? If not then how can I programmatically click links which will also fire mousedown/mouseup events?

1
  • looks like you're putting all that js into an onclick attribute of a link or a button. It might be easier for you to debug if you put it into a function and call that function instead. Commented Sep 17, 2012 at 14:24

1 Answer 1

1

You're coming across the usual "loop variable in a lambda" problem: by the time the timeout is done, i will be past the end of document.links and l[i] will be undefined. You could just wrap that part in a(nother) function:

(function(item) {
    setTimeout(function() { clickLink(item); }, 1000);
})(l[i]);
Sign up to request clarification or add additional context in comments.

3 Comments

That solves the problem.. Thanks. BTW clicking links this way will fire mouseup/mousedown event?
@JamesSmith: No, it won't. You'll need separate events for those.
Can you please tell me how can I do that? I also need to fire the mousedown/mouseup events while clicking links by bookmarklet?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.