1

I'm experimenting with some JavaScript code and run into a problem where an element tells me can't be clicked. The goal is to activate a tab based on the anchor in the URL. Here's the short version:

<tab onClick="showTab('Dogs')">Dogs</tab>
<tab onClick="showTab('Cats')">Cats</tab>
<script type="text/javascript">
var chunks = document.URL.split('#')
if(chunks.length > 1) {
  var anchored_tab = chunks.pop().toLowerCase()
  var tabs = document.getElementsByTagName('tab')
  for(i in tabs) {
    if(tabs[i].innerHTML.toLowerCase() == anchored_tab) {
      alert("trying to click tab "+tabs[i].innerHTML)
      tabs[i].click()  // TypeError: Object#<HTMLElement> has no method 'click'
    }
  }
}
</script>

Assuming the URL ends with "#dogs", the alert correctly says "trying to click tab Dogs", but then I get an exception on the next line saying the element doesn't have a click method.

I'm testing on Chrome 12.

wersimmon
  • 2,809
  • 3
  • 22
  • 35

2 Answers2

0

You can add the following code somewhere above what you have now, which will add a trigger event to the actual click event in browsers that don't let you click() directly. Please note that this type of functionality is often wrapped up in a library such as jquery or prototype.

if(typeof HTMLElement!='undefined'&&!HTMLElement.prototype.click) {
    HTMLElement.prototype.click=function() {
        var evt = this.ownerDocument.createEvent('MouseEvents');
        evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
        this.dispatchEvent(evt);
    }
}
Jordan
  • 31,971
  • 6
  • 56
  • 67
0

not all browsers support click() on html elements. you can try .onclick() but your best bet would be to use a cross browser supported click event trigger like in jQuery or another js library

checkout this old post for more info

Community
  • 1
  • 1
pthurlow
  • 1,091
  • 7
  • 11