Imitate user by clicking link

I need to click a link when a key is pressed, I prepared this jQuery:

   $('form#form1').bind("keypress", function(e){
        if(e.keycode == 13 || e.keyChar == 13 || e.which == 13){
        $('.LoginBoxButton a').click();
        }   
    });

      

It doesn't work and I read the following explanation why:

It's important to remember that click () will not trigger the on-link behavior by default, even if nothing else gets in the way. Thus, you cannot use click () yourself to simulate a user clicking on a link and taken to a different url.

But how do you simulate a user clicking on a link and being taken to another URL?

+2


a source to share


3 answers


You can do the following:



$('form#form1').bind("keypress", function(e){
    if(e.keycode == 13 || e.keyChar == 13 || e.which == 13){
      document.location.href = $('.LoginBoxButton a').attr('href');
    }   
});

      

+4


a source


But how do you simulate a user clicking on a link and being taken to another URL?

They are two different things:

The first, simulating a user click, is a fairly low-level task. I would suffocate on a browser that allowed it unlimited.

Second, navigating the user to a different url is as easy as assigning the url you want document.location.href

.

So instead of



$('.LoginBoxButton a').click();

      

using

document.location.href = $('.LoginBoxButton a').attr('href');

      

Hope it helps.

+2


a source


First of all jQuery Event.which normalizes event.keyCode

and event.charCode

- so you don't need to check keyCode

/ charCode

.
Second, decide if you want to simulate a user click on an element or just redirect to another location, because there is a huge difference between one and the second. While the latter is redirecting the former, do all associated events mousedown

/ mouseup

/ first click

(in the given order). Also, if the event click

returns false

, the redirection should be blocked.

So the code for the first situation has already been set, but here is the code for the true simulation:

<a href="test.html">LsINK</a>
<span>ROBOT</span>

$("a").mousedown(function() { alert("mousedown"); })
      .mouseup(function() { alert("mouseup"); })
      .click(function() { alert("click"); return false; });

$("span").click(function() {
    if (false !== $("a").mousedown().mouseup().triggerHandler("click")) {
        alert("Redirect to: " + $("a").attr("href"));
        //window.location.href = $("a").attr("href");
    }
});

      

+1


a source







All Articles