Simulating href click

Discussion in 'JavaScript' started by cesarcesar, Sep 16, 2008.

  1. #1
    i need to simulated having clicked on a link with JavaScript. As you will see in my stripped down example the resulting function from the click is a window.addEvent() action. Thanks for the help.

    js code -
    
    window.addEvent('domready', function() {
         expandCollapse();
    }
    
    function expandCollapse(){
         $('expand').addEvent('click', function(){
              // do something
         }
    }
    
    Code (markup):
    html code -
    <a id="expand" href="javascript:void(0);">open all</a>
    Code (markup):
    i have tried this but id didnt work -
    document.getElementById('expand').click();
    Code (markup):
    What is the code to make the window.addEvent() fire? *expand* must be part of it. Thank you.
     
    cesarcesar, Sep 16, 2008 IP
  2. cesarcesar

    cesarcesar Peon

    Messages:
    188
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Thanks to Fang -

    Working Solution -
    
    function fireOnclick(objID) {
    var target=document.getElementById(objID);
    if(document.dispatchEvent) { // W3C
        var oEvent = document.createEvent( "MouseEvents" );
        oEvent.initMouseEvent("click", true, true,window, 1, 1, 1, 1, 1, false, false, false, false, 0, target);
        target.dispatchEvent( oEvent );
        }
    else if(document.fireEvent) { // IE
        target.fireEvent("onclick");
        }    
    }
    
    Code (markup):
     
    cesarcesar, Sep 16, 2008 IP