Royi Namir
Royi Namir

Reputation: 148744

About to solve simulating click on Href anchor?

I was looking for a way to simulate a click on <a> tag

as you all know , no success ( the only workaround is by window.open...)

however i found some peaces of code in the net and managed to make it work in :

http://jsbin.com/itujek/5/edit

Chrome
IE

the problem is with FF.

I'll be glad to share the code with you , and towards a solution which will wrk in FF.

what should i do in this code in order for this code wo work with FF ?

  <script>
        function doClick(event, myA)
        {
            if (myA.click)
            {
                myA.click()
            }
            else if (document.createEvent)
            {
                if (event.target !== myA)
                {
                    var tmpEvent = document.createEvent("MouseEvents");
                    tmpEvent.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
                    var allowDefault = myA.dispatchEvent(tmpEvent);
                }
            }
        }


      $(document).ready(function(){

            $(".myBtn").on('click',function (event) 
                           { doClick(event, $("#link")[0]);    });
      });



    </script>
</head>
<body>
    <a id="link" href="http://www.msdn.com">Normal link</a>
    <button type="button" class="myBtn"   >
        do click</button>
    <br />
    <br />
</body>

Upvotes: 1

Views: 2160

Answers (4)

Rory McCrossan
Rory McCrossan

Reputation: 337713

It's for occasions like this that I prefer to avoid 'faking' events. Have you tried reding the href and redirecting to it manually? Try this:

$(".myBtn").on('click', function(event) {
    doClick($("#link"));
});


function doClick($el) {
    var href = $el[0].href;
    if ($el.attr("target") != "_blank") {
        window.location.assign(href );
    }
    else {
        window.open(href, "newWindow");
    }
}

Example fiddle

Upvotes: 0

Vithozor
Vithozor

Reputation: 620

Instead of

if (myA.click){
    myA.click();
}

you can do

if (myA.click){
    window.location.href = myA.href;
}

Another thing, on the line if (e.target !== myA) the variable eis not defined, it should be event.

Upvotes: 0

Nhu Trinh
Nhu Trinh

Reputation: 13986

Look at the code here

if (myA.click)
{
   myA.click()
}

maybe your firefox element has .click attribute so it just call the function click (event) not actually do the redirect. My suggest is just remove this part and simulate a real click. Or You may want to simulate redirect by using window.location.href = anchor.href

Upvotes: 0

Engineer
Engineer

Reputation: 48813

You may try to use jquery.simulate.js :

$(elem).simulate(mouse_or_keyboard_event_type, options);

Supported event types:

  • mouse: mouseover, mouseout, mousedown, mouseup, mousemove, click, dblclick
  • keyboard: keyup, keydown, keypress

Upvotes: 2

Related Questions