andyjv
andyjv

Reputation: 583

Trying to prevent default click and run a function instead

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);
}

Upvotes: 2

Views: 2549

Answers (4)

avetarman
avetarman

Reputation: 1252

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

    function loader(event){
    theLink = event.target;
    alert("You clicked: " + theLink);
    }
});

Upvotes: 2

brenjt
brenjt

Reputation: 16297

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);
}

Upvotes: 2

Jayantha Lal Sirisena
Jayantha Lal Sirisena

Reputation: 21366

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

Upvotes: -1

Alastair Pitts
Alastair Pitts

Reputation: 19601

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);
}

Upvotes: 1

Related Questions