Event click on href <a> tag
ajax, javascript, jquery, jquery-events, magento
Solution
Explanation
Redirects can only happen if the user clicks directly on the link. Programmatic or deferred `click` triggers do not work.
An alternative would be:
- to change directly the `window.location`
- to open the link in a new tab/window
Changing `window.location`
window.location="http://wherever.you/want/to/g0";
or
window.location=$('a.selector').attr('href'); // to use a link's address
New tab/window
You cannot programmatically (`click()` or `trigger`) open new tabs/ windows or redirect. They get (ad-)blocked. automatically
So new tab/window openings always have to be triggered by user action. (Otherwise we'd always be full with popup ads)
So 1st of all, make sure that your js is executed on a user event, and then you should be able to use `window.open`.
JsFiddle example
html:
<a href="//google.com" target="blank">new tab google</a>
<button class="user">user triggered</button>
<button class="programatic">programatic</button>
js:
$('a').on('click', function(e) {
console.log('clicked', e);
// unfortunately although we simulated
// the click on the <a/> , it will still
// not launch a new window - idk why.
// therefore we can use the line below
// to open the <a>'s href in a new tab/window
// NOTE: this will only occur if the execution was
// triggered by the user
window.open(e.currentTarget.href);
});
var simulateClick = function(origEv) {
var e = $.Event("click");
e.ctrlKey = true;
e.metaKey = true;
e.originalEvent = origEv;
$('a').trigger(e);
};
$('button.user').on('click', function(e) {
// this call will actually open a window
simulateClick(e);
});
$('button.programatic').on('click', function(e) {
// this will result in a blocked popup
$.get('/someurl').always(function() {
// executes the method after a non-user event
// results in blocked popup
simulateClick(e);
});
});
// this will result in a blocked popup
setTimeout(simulateClick, 1000);
Problem
I have a question about Javascript event here. I have an `<a>` tag like this: `<a id='aTag' href='http://example.com'>Click to redirect</a>` Then I call an event like: ``` <script> $('#aTag').click(); //or $('#aTag').trigger('click'); </script> ``` It does not redirect me to `http://example.com`. I tried to add an `onClick()` event in the `<a>` tag like this: ``` <a id='aTag' href='http://example.com' onclick='alert("Event happened");'>Click to redirect</a> ``` And then call the `.click()` event. It shows me `alert("Event happened")`; Can anyone show me how to call the `.click()` event correctly, or correct this redirect with issue with the `href` in that `<a>` tag? In my business I just need an `<a>` tag, so not with the `window.open` or `windown.location`.