Sumeet Sheokand

Navigation

Skip navigation.

Search

Site navigation

Email conversation

FromSumeet Sheokand
ToMe
SubjectMouseEvents-click on a link not working...
Date31 October 2006 04:18
Hi There,
  Thanks for an excellent tutorial at
http://www.howtocreate.co.uk/tutorials/javascript/domevents. I
followed it all the way to the bottom and it works as described. I
tried to take it a step further and that is where I failed. I am
trying to simulate a user clicking a link on the browser. The code
is...

The HTML document contains this link...

<a href="javascript:alert('Got Here');">Some Text</a>

The script has...

var links = document.links;
for(var i = 0; i < links.length; i++) {
    if(links[i].text == "Some Text"){
       alert(links[i].text); //this works..
       var evObj = document.createEvent('MouseEvents');
        evObj.initMouseEvent( 'click', true, false, window, 0, 0,0,0,0,
false, false, true, false, 0, null );
        links[i].dispatchEvent(evObj);
   }
}

As you can see, I followed your example and expected the click to be
fired, but its not. Do you have any ideas why that may be and what I
can do to fix it.

Thanks for your time,
Sumeet.
FromMe
ToSumeet Sheokand
SubjectRe: MouseEvents-click on a link not working...
Date31 October 2006 07:57
Sumeet,

> <a href="javascript:alert('Got Here');">Some Text</a>

The click event is fired correctly, but this link will never be activated by
a simulated click.

Firing the click event just runs the click event handlers. It does not
actually click the link. See the line of the tutorial where I say: "Note
that manually firing an event does not generate the default action
associated with that event."

You can assign the href of the link to the location.href object. However,
your current approach will fail completely if JavaScript is disabled, and
this would be my personal approach that avoids that problem:

<a href="nextpage.html"
onclick="javascript:alert('Got Here');return false;">Some Text</a>
...
links[i].onclick();


Mark 'Tarquin' Wilton-Jones - author of http://www.howtocreate.co.uk/
This site was created by Mark "Tarquin" Wilton-Jones.
Don't click this link unless you want to be banned from our site.