Sergio
Sergio

Reputation: 1239

Jquery preventDefault of another function

The function in a sample of my Jquery code looks like:

$(document).on("click",".delete", function(del) {
    var foo='del';
    connect(foo);
    alert("connected");
});

And the "connect" function looks like:

function connect(foo){
    var networkState = navigator.network.connection.type;
    if (networkState == Connection.NONE){   
        navigator.notification.alert('There is no connection.','','Error','Ok');    
        foo.preventDefault();
    }
}   

What I need is to "connect" function after checking internet connectivity stops executing other functions. In this case, function "del" before executing alert.

With this code I get an error message "Uncaught ReferenceError: del is not defined at file..." What will be the right solution for this?

Upvotes: 0

Views: 102

Answers (2)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93551

jQuery event handlers typically pass an object of type jQuery.Event

You need to have (or generate) an object of this type to have the preventDefault() function present to call on it.

You can either pass the one from the click handler, or, if you prefer, create a new one.

To use the existing click event object simply pass it through e.g.:

$(document).on("click",".delete", function(del) {
    connect(del);
    alert("connected");
});

To use a new event object:

var foo = jQuery.Event( "del" );
connect(foo);

In fact your only mistake appears to be putting quotes around del

Upvotes: 0

Oriol
Oriol

Reputation: 287960

You must pass the event to the other function. Currently, you pass the string 'del' instead of the variable del (the event).

$(document).on("click",".delete", function(event) {
    connect(event);
});

To avoid confusion, I suggest using event (or e) instead of del or foo.

Upvotes: 1

Related Questions