Search code examples
phphtmlcssjscriptconfirm

Prevent Default Not working Jscript if(confirm){}else{prevent default}


i did have this working correctly, but now iv altered my html markup since and i think im missing sum thing,

The Code explains it all, But Its not preventing default if not confirmed.

Can anybody see what the problem is,

Most grateful for any info.

Thanks

<?
    if (!empty($facebook)) {echo"<a href='#'onClick=\"facebookalert(); MyWindow=window.open('{$facebook}','MyWindow','width=365,height=300'); return false;\"></a>"; }

?>                                  


function facebookalert(){
if (confirm("You will be Forwarded to the sellers FACEBOOK account to make contact\nYou can return to this website as this window will not close\nThank you")) {
} else {
event.preventDefault();
     return false;
}

};

Solution

    1. you need to pass the event object to facebookalert function if you want to use event.preventDefault().

    2. event.preventDefault(); is not what you want to use to prevent that window from opening.

    Use like this instead

    <?
        if (!empty($facebook)) {echo"<a href='#'onClick=\"if(facebookalert()){window.open('{$facebook}','MyWindow','width=365,height=300'); return false;}\"></a>"; }
    
    ?> 
    

    and then, just returning false would do

    function facebookalert(){
    if (confirm("You will be Forwarded to the sellers FACEBOOK account to make contact\nYou can return to this website as this window will not close\nThank you")) {
       return true;
    } else {
         return false;
    }
    
    };
    

    From W3C The event.preventDefault() method stops the default action of an element from happening.

    For example:

    Prevent a submit button from submitting a form.

    Prevent a link from following the URL.

    It does not abort the window.open from executing.