Reputation: 5664
I have a jquery for anchor tag in which it calls for ajax first time and then when the success is returned it calls click again. On the second call it returns true but the anchor link doesn't work.
Below is my code
Html:
<a href="#" class="test-link" target="_blank">test</a>
jQuery:
$(document.ready(function(){
$('.test-link').click(function(){
if ($(this).hasClass('test')){
$(this).removeClass('test');
return true;
} else {
$.ajax({
...
...
success : function(data) {
$('.test-link').attr('href',data.url).addClass('test').click();
}
});
return false;
}
});
This doesn't work for me and i also tried using preventDefault(); but no use.
Note : On the very first click, it calls the ajax and when it is a success, it sets the url of anchor and class and then calls the click again,
But the click doesn't navigate to other page.
Upvotes: 1
Views: 1255
Reputation: 17
This opens the page in new tab not in pop-up
window.open(url,'_blank');
I think it should be,
if ($(this).hasClass('test')){
$(this).removeClass('test');
window.open($(this).text(),'_blank');
}
Upvotes: 0
Reputation: 150010
You can use window.open()
, but as far as getting click()
to work you can do this:
$('.test-link').click(function(){
if ($(this).hasClass('test')){
$(this).removeClass('test').off('click'); // unbind click handler
this.click(); // call native click()
} else {
$.ajax({
...
...
success : function(data) {
$('.test-link').attr('href',data.url).addClass('test').click();
}
});
return false;
}
});
Using this.click()
will directly call the DOM element's click()
method rather than the jQuery click()
method - I've found in the past this will cause the default behaviour for a link to actually work (i.e., it will navigate to the specified url), whereas the jQuery click()
method will execute the handler you've assigned but not actually navigate.
But also you need to unbind the click handler so that it doesn't go into an endless loop. Which means from then on the link will always open that same URL in a new tab, it won't make further Ajax requests. Is that acceptable?
Demo: http://jsfiddle.net/Pdwt8/1/
Upvotes: 1
Reputation: 55740
Triggering the click event of an anchor does not redirect to the page specified automatically.
You have to click the link explicitly to navigate to a different page..
You can use
window.open('','','width=200,height=100') ; // instead`
You can try this approach
if ($(this).hasClass('test')){
$(this).removeClass('test');
window.open('','','width=200,height=100')
}
Upvotes: 1