Click a link with JavaScript

Here is some code that shows you how you can click a link with JavaScript (without using the mouse):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="" />
    <title>Click a link with JavaScript</title>
    <style type="text/css">
      * { margin: 0; padding: 0; border: 0; }
    </style>
  </head>
  <body>
    <a id="myLink" href="https://www.bennyn.de/">Hyperlink</a>
    <script type="text/javascript">
      function clickLink(id){
        var theEvent = document.createEvent("MouseEvent");
        theEvent.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        var element = document.getElementById(id);
        element.dispatchEvent(theEvent);
 
        while (element){
          if (element.tagName == "A" && element.href != ""){
            if (element.target == "_blank") { window.open(element.href, element.target); }
            else { document.location = element.href; }
            element = null;
          }
          else{
            element = element.parentElement;
          }
        }
      }
 
      clickLink('myLink');
    </script>
  </body>
</html>

Create a link with an image in JavaScript

With JavaScript you can dynamically create every HTML element that you want. Here is an example on how to create a link with an image:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Create a link with an image in JavaScript</title>
    <style type="text/css">
      .googleImage{ border: 2px solid blue; }
    </style>
  </head>
  <body>  
    <script type="text/javascript">
      // Link
      var link = document.createElement('a');
      link.href = 'http://www.google.de/';
      // Alternative:
      link.setAttribute('href', 'http://www.google.de/');
 
      // Image
      var image = document.createElement('img');
      image.className = 'googleImage';
      image.src = 'http://www.google.de/images/logo.png';
 
      // Create a link with an image inside
      link.appendChild(image);
      // Display the link
      document.body.appendChild(link);
    </script>
  </body>
</html>

Link-Text durch Grafik ersetzen

Möchte man in einem vorgegebenen Link den Text unsichtbar machen und durch ein Hintergrundbild ersetzen, so ist das Erste was einem einfällt color: transparent; für die Linkfarbe. Leider ist diese Eigenschaft nicht spezifiziert in CSS 2.1.

Trotzdem möchte ich eine Möglichkeit zeigen, die nach CSS 2.1 gültig ist und im Internet Explorer 6-8 sowie im Mozilla Firefox funktioniert.
Link-Text durch Grafik ersetzen weiterlesen