0

I have an <a href="javascript:addProduct('myParam')" id="myLink">add product</a> that does

  1. adds a new product,
  2. displays a content as a link, and
  3. does not navigate away from the page.

How to rewrite it to jQuery?

<a href="#" id="myLink">add product</a>
and
$("#myLink").click(addProduct('myParam'));

would navigate away on click(?!)...

serge
  • 13,940
  • 35
  • 121
  • 205

2 Answers2

3

Update addProduct to take an event parameter - then call event.preventDefault(); to stop the default link action:

function addProduct(e) {
    e.preventDefault();
    //code...
}

Your current handler $("#myLink").click(addProduct('myParam')); won't work how you think. addProduct is going to be executed immediately if you do this, because using () at the end of the function actually calls it!

Quick example on passing functions:

var x = function() {
    return 3;
}

var y = x; //assigned the function of x
y(); //3
var z = x(); //3

If you want to pass a param (other than the default ones) - you'll have to use an anonymous function and then call your function from that:

$("#myLink").click(function(e) {
    addProduct(5, e);
});
tymeJV
  • 103,943
  • 14
  • 161
  • 157
2

I think you're looking for this:

$("#myLink").click(function(e){
    e.preventDefault();
    addProduct(e.target);
});
Alex Slipknot
  • 2,439
  • 1
  • 18
  • 26