Caves Travel Diving Graphics Mizar Texts Cuisine Lemkov Contact Map RSS Polski
Trybiks' Dive Texts HTML Clicking on links in JavaScript YAC Software
  Back

List

Charsets

Charts

DBExpress

Delphi

HTML

Intraweb

MSTest

PHP

Programming

R

Rhino Mocks

Software

Testing

UI Testing

VB.NET

VCL

WPF

Clicking on links in JavaScript
Let's say that you have a link on your page and you want to simulate a click on it.

Don't ask that question on forums, because most of the answers you'll get is that you shouldn't simulate the click at all and that you should just use location.href instead. And that your whole idea is wrong, etc...

The problem I head was that I wanted to show a page full of small images. When a user clicks on an image, a highslide window opens presenting a larger version of the image.

Next, I wanted to create links to these pages, but in such a way, that the highslide window automatically opens for the chosen image. Obviously, redirection is not the solution here...

Ok, idea #1: just get the element by its ID and call click() on it:
  var elem = document.getElementById( imageID );
  if( elem )
    elem.click();
Nice and simple, but... doesn't work in Firefox (works in IE and Opera though).

Ok, some searching on the web, looking through numerous and totally irrelevant comments, when finally this was mentioned:
  var elem = document.getElementById( imageID );
  if( elem )
  {
    var evt = document.createEvent( "MouseEvents" );
    evt.initMouseEvent(
      "click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null );
    elem.dispatchEvent( evt );
  }
Ahh... started working in Firefox, works in Opera, but stopped working in IE. Never a break!

Thus the final version:
  var elem = document.getElementById( imageID );
  if( elem )
  {
    if( elem.dispatchEvent )
    {
      var evt = document.createEvent( "MouseEvents" );
      evt.initMouseEvent(
        "click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null );
      elem.dispatchEvent( evt );
    }
    else
      elem.click();
  }
HTH

Top

Comments
Alas!
No comments yet...

Top

Add a comment (fields with an asterisk are required)
Name / nick *
Mail (will remain hidden) *
Your website
Comment (no tags) *
Enter the text displayed below *
 

Top

Tags

HTML


Related pages

Fix for Highslide HTML Slides

Calculating Positions of HTML Elements

CSS for Scrollbars on Pages and in Frames

</form> ... <form>