Understanding event bubbles in javascript

I tried to understand even the bubbles, and I'm not quite sure that I am completely following it. I started reading about this to alert users when they leave a page on my website if they start entering data into the form (similar to how StackOverflow does it!).

The following code seems to work in a cross browser:

var entereddata = false;

$(document).ready(function()
{
    $('#contactform').bind('keypress',function(e) {
            if((e.which > 96 && e.which < 123) || (e.which > 47 && e.which < 58)) {
                    entereddata = true;
                    //alert(e.which);
            }
    });
});

function confirmLeave(e, d)
{
    if(!e) e = window.event;//window.event;
    if(!d) d = entereddata;

    var confirmationMessage = 'It appears you have started to enter information into the contact form, but have not yet submitted it';

    if(!d)
    {
            e.cancelBubble = true;
    } else
    {
            return confirmationMessage;
    }
}

window.onbeforeunload=confirmLeave; 

However, this also gets called when I click the submit button for the form I don't want. I tried various code additions, such as adding:

if($('#submit').click()){
    submitted=true;
} else {
    submitted=false;
}

if (! d) if (! d && == false) ; , ( , ) , , , , - !

, - , e.cancelBubble = true; , .

, :

  • , , , .
  • eventBubbling; : inputData , . ? e.cancelBubble = false, inputData , e.cancelBubble = true, inputData ? e.cancelBubble ?

, e.stopPropagation , firefox ?

, - .

,

+5
4

?

$('#submit').click(function() {
    entereddata = false;
});

, .. , confirmLeave , .

0

"" onbeforeunload:

$('#submit').click(function() {
    window.onbeforeunload=null;
});

, ...

null, , , , , , ...

function confirmLeave(e) {
    e = e || window.event;//window.event;

   var confirmationMessage = 'It appears you have started to enter information into the     contact form, but have not yet submitted it';

    if(entereddata) {
          return confirmationMessage;
    } else {
            return null;
    }
}

Bubbling and distribution apply only to an event that should notify it of children or parents, and as far as I know, window.onbeforeunload is a global event that will not be distributed.

0
source

Not related to bubbles, but you can bypass the detection of whether keys were pressed and check the form data instead:

function hasNonemptyTextInputs() {
    var textInputs = $('#contactform :input').filter(':text, textarea');

    // Check for any field with a nonempty value
    // .is() returns true iff the function returns true on any element
    return textInputs.is(function() {
        return $(this).val().length > 0;
    });
}
0
source

All Articles