Search code examples
jqueryeventsclick

Why is jQuery click-event triggered when page loaded?


I have the following code.... When the page is loaded myFunc() is called even if I dont click in my div. Why? The function declared "inline" is not triggered...hmmmm........

<div id="map" style="background: green; height: 100px"></div>

<script type="text/javascript">
    function myFunc() {
        alert("allways triggered when page loads...");
    };

    $(document).ready(function() {

    $("#map").click(myFunc());
    $("#map").click(function() { alert("not triggered") });

    });
</script>

Solution

  • Because of your code:

     $("#map").click(myFunc());
    

    is wrong and has to be:

    $("#map").click(myFunc);
    

    Your code would call myFunc() first and than simulate a onclick event.

    As seen in the documentation:

    What you did is this: (as myFunc returns null)

    click( )

    Triggers the click event of each matched element. Causes all of the functions that have been bound to that click event to be executed. To trigger the click event on all of the paragraphs on the page: $("p").click();

    What you want is this:

    click( fn ) Binds a function to the click event of each matched element. The click event fires when the pointing device button is clicked over an element. A click is defined as a mousedown and mouseup over the same screen location. The sequence of these events is: