Search code examples
jqueryjquery-eventsevent-bubbling

How can I get event bubbling to work when a div is clicked the first time?


I'm making a calendar. I want the user to be able to click anywhere inside a particular day (table cell) and something happens. There may be events for that day, which are contained inside a div within the table cell. If the user clicks on the div, then something else happens. I have managed to prevent event bubbling when the user clicks on doSomethingElse(), but it doesn't work the first time it is clicked. It only works on subsequent clicks, never on the first click. Why doesn't the cancelling of event bubbling work on the first click, and only works on all subsequent clicks?

HTML:

<table>
    <tr>
        <td onclick="doSomething()">
            <div class="view" onclick="doSomethingElse()">Text</div>
        </td>
    </tr>
</table>

Javascript:

function doSomethingElse() {
    $('.view').click(function(e){
        e.cancelBubble = true;
        e.returnValue = false;

        if (e.stopPropagation)
        {
            e.stopPropagation();
        }
    });

    $('#myID').load('myFile.php');
}

UPDATE: I put this on my page:

<script>
$(document).ready(function() { 
    $('.view').click(function(e){
        e.cancelBubble = true;
        e.returnValue = false;

        if (e.stopPropagation)
        {
            e.stopPropagation();
        }
    });
});
</script>

Then, the onclick="doSomethingElse()" just contains the rest of my script. The problem is that doSomethingElse() has parameters, so it seems like I need to still have the following:

<div class="view" onclick="doSomethingElse(id1,id2)">Text</div>

It still only works on the 2nd, 3rd, ... clicks, but not the first.


Solution

  • Because you've effectively written binding code in your onclick handler. Put your click binding (the $('.view').click part) in your document ready. Also, why is the load outside the handler?