I am trying to override the default behaviour of an anchor tag so i can load in a web page on my server into the exisiting div, rather than a new tab or window.
so far i have:
myContainer.click(function(){
event.preventDefault();
$('a').click(function(){
var link = $(this).attr('href');
myContainer.load(link);
});
});
In chrome i have to click the link twice before it does anything, in IE an FF it doesnt work at all and refreshes the page with the new link.
Any help is much appreciated.
Shouldn't it be just:
$('a').click(function(e) {
e.preventDefault();
myContainer.load(this.href);
});
Your code assigns a click handler inside a click handler. So the first click will attach the click handler to the link, and the second click (on the link) will execute the new click handler.
It seems you only need one click handler. If the links are added dynamically, you can use .on()
(the successor of .live
and .delegate
):
myContainer.on('click', 'a', function(e) {
e.preventDefault();
myContainer.load(this.href);
});
// or
$(document).on('click', 'a', function(e) {
e.preventDefault();
myContainer.load(this.href);
});
you forgot to pass in event:
myContainer.click(function(event){
event.preventDefault();
$('a').click(function(){ var link = $(this).attr('href');
myContainer.load(link);
});
});
try to rearrange them:
myContainer.ready(function(){
$('a').click(function(event){
event.preventDefault();
var link = $(this).attr('href');
myContainer.load(link);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With