2

I'm pretty new to JS and jQuery, and I've just gotten enough grasp on basic JS to try some things out in jQuery. So what I'm trying to do here is prevent pages from loading when a link in the main navigation is clicked (and ideally would load the page with ajax instead).

So this is my script so far, and basically nothing is working... in Chrome, the alert shows up and displays the link that was clicked, but Firefox4 seems to ignore my script altogether (Firebug console shows nothing).

Any help is appreciated.

$(document).ready(function(){
$("#navigation a").each(function() {
    $(this).click(function(){
        event.preventDefault();
        loader();
    });
});

});

function loader(){
theLink = event.target;
alert("You clicked: " + theLink);
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
andyjv
  • 583
  • 1
  • 8
  • 24

4 Answers4

2

Try updating your code to this

$(document).ready(function(){
    $("#navigation a").click(function(event){
        event.preventDefault();
        loader(event);
    });
});

function loader(event){
    var theLink = event.target;
    alert("You clicked: " + theLink);
}
brenjt
  • 15,997
  • 13
  • 77
  • 118
2
$(document).ready(function(){
    $("#navigation a").click(function(event){
            event.preventDefault();
            loader(event);
        });                

    function loader(event){
    theLink = event.target;
    alert("You clicked: " + theLink);
    }
});
avetarman
  • 1,244
  • 9
  • 8
1

you aren't passing in the event object to your click handler. Also, you don't need the .each()as the .click() will enumerate the results of your query and attach a click handler to each of them

try adjusting it to:

$(document).ready(function(){
    $("#navigation a").click(function(e) {
            e.preventDefault();
            loader(e);
        });
    });
});

function loader(e){
    theLink = e.target;
    alert("You clicked: " + theLink);
}
Alastair Pitts
  • 19,423
  • 9
  • 68
  • 97
-1

Try adding return false at the end of the click function

 $(this).click(function(){
        event.preventDefault();
        loader();
        return false;
    });

and read this event.preventDefault() vs. return false

Community
  • 1
  • 1
Jayantha Lal Sirisena
  • 21,216
  • 11
  • 71
  • 92