never_had_a_name
never_had_a_name

Reputation: 93236

jquery executes declared function without me clicking

i wonder why the browser displays "logged in" without me having clicked on the link i id-tagged with clickhere. it displays it everytime i refreshes the page.

<script type="text/javascript">
  $(document).ready(function(){

    function login(){
       alert("logged in");
    }

    $("#clickhere").click(login());

 });
</script>

i just want it to be displayed when i click on the link.

what is the problem?

Upvotes: 0

Views: 310

Answers (2)

Ei Maung
Ei Maung

Reputation: 7153

You have to pass the method to jQuery's click(). login() mean execute-the-login-method. You have to pass method correctly as ammoQ said.

Or you can change your code like this. It will only call login() when click the #clickhere.

<script type="text/javascript">
  $(document).ready(function(){

    function login(){
       alert("logged in");
    }

    $("#clickhere").click(function() {
        login();
    });

 });
</script>

Upvotes: 0

Erich Kitzmueller
Erich Kitzmueller

Reputation: 36987

You have to remove () after login in JQuerys click() function.

<script type="text/javascript">
  $(document).ready(function(){

    function login(){
       alert("logged in");
    }

    $("#clickhere").click(login);

 });
</script>

Upvotes: 5

Related Questions