Andrew
Andrew

Reputation: 511

jQuery click function called as soon as page loads

I have a jQuery script that basically is changing my css when I click a link:

jQuery("a.adder").click(css_change());

My problem is that when I first load the page, the css_change() is being fired even when the link hasn't been clicked. I know this for sure cause I changed the css_change() into alert("here") and that alert showed up. Anyone have any ideas as to why this is happening?

Upvotes: 4

Views: 1226

Answers (2)

Andrew Whitaker
Andrew Whitaker

Reputation: 126082

css_change()

Is immediately executing the function upon binding.

Use:

jQuery("a.adder").click(css_change);

(pass a reference to the function instead of the results of executing the function).

Upvotes: 5

Gabe
Gabe

Reputation: 50523

Remove the parenthesis on the function call.

jQuery("a.adder").click(css_change)

Upvotes: 1

Related Questions