Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding default behaviour of anchor tags using jquery

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.

like image 317
Julio Avatar asked Mar 05 '11 23:03

Julio


2 Answers

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);
});
like image 71
Felix Kling Avatar answered Oct 24 '22 13:10

Felix Kling


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);
     });
     });
like image 41
DrStrangeLove Avatar answered Oct 24 '22 13:10

DrStrangeLove