I want to create function that can be used either with Id or by passing jQuery object.
var $myVar = $('#myId');
myFunc($myVar);
myFunc('myId');
function myFunc(value)
{
// check if value is jQuery or string
}
How can I detect what kind of argument was passed to the function?
Note! This question is not same. I don't want to pass selector string like #id.myClass
. I want to pass the jQuery object like in the example.
This post shows how to check if a function exists, before calling it. We will use both JavaScript as well as jQuery (JavaScript library) to do so. jQuery contains the jQuery. isFunction() which finds out if the parameter passed to it is a function.
$(this) is a jQuery wrapper around that element that enables usage of jQuery methods. jQuery calls the callback using apply() to bind this . Calling jQuery a second time (which is a mistake) on the result of $(this) returns an new jQuery object based on the same selector as the first one.
To check if an element was clicked, add a click event listener to the element, e.g. button. addEventListener('click', function handleClick() {}) . The click event is dispatched every time the element is clicked.
function myFunc(value)
{
if (typeof value == "string") {
//it's a string
}
else if (value != null && typeof value == "object"} {
//it's an object (presumably jQuery object)
}
else {
//it's null or something else
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With