Reputation: 148744
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
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");
}
}
Upvotes: 0
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 e
is not defined, it should be event
.
Upvotes: 0
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
Reputation: 48813
You may try to use jquery.simulate.js :
$(elem).simulate(mouse_or_keyboard_event_type, options);
Supported event types:
Upvotes: 2