Search code examples
jqueryanchorhrefpreventdefault

Anchor click preventDefault and then turn back on


Below is problem and code:

I'm clicking on an anchor which has an href set already.

Step1, upon anchor fileMove click, I'm preventing it from firing original href because I'm opening a popup for user to click something and provide some info.

$('#fileMove').click(function(e) {
    alert($('#fileMove').attr('href'));
    e.preventDefault(); //prevent original href
    showdevDialog(); //dialog popup call
});

function showdevDialog() {
    $('#JQueryFTD_Demo').dialog(); //dialog with div JQueryFTD_Demo
}

// this will be in document.ready
$('#JQueryFTD_Demo').fileTree({
    root: 'D:\\Test',
    script: '../jqueryFileTree.jsp',
    expandSpeed: 1000,
    collapseSpeed: 1000,
    multiFolder: true,
    loadMessage: 'Please Wait While Loading...'
    }, function(file) {
        //alert(file);
    }, function(dir){
        moveFileToFolder(dir); //once user selects a folder passing 
                                              //it to function          
});

This function hides the popup and then constructs a new href using the folder name then binds click event.

function moveFileToFolder(dir) {
    $('#JQueryFTD_Demo').hide();
    $('#JQueryFTD_Demo').dialog('close');
    var _href = $('#fileMove').attr("href");
    $('#fileMove').attr("href", _href + '&moveto=' + dir);
    alert($('#fileMove').attr('href'));
    $('#fileMove').unbind('click').click();
    //$('#fileMove').attr('href')
    //alert("Inside func.. " + dir);
}

But the click event once again calls $('#fileMove').click() which has preventDefault and nothing happens.

How do I get around this problem?

Any help appreciated.


Solution

  • You could use the .preventDefault() conditionally only when the dialog is visible by doing something like this:

    $('#fileMove').click(function(e){
        alert($('#fileMove').attr('href'));
        if ($("#JQueryFTD_Demo:visible"){
            e.preventDefault(); //prevent orignal href
            showdevDialog(); //dialog popup call
        };
    
    });