Jquery check if var is a function and then call it - javascript

I have a variable name that I pass into a plugin, but the variable is actually a function.
I use jquery $.isFunction to check if it is a function, and if it is, it should execute the function.
But I can't seem to make it work, I put some examples in jsfiddle:http://jsfiddle.net/tZ6U9/8/
But here is a sample code:
HTML
<a class="one" href="#">click</a><br />
<a class="two" href="#">click</a><br />
<a class="three" href="#">click</a><br />
JS
$(document).ready(function() {
help = function(var1) {
alert(var1);
}
function help2(var1) {
alert(var1);
}
$('a.one').click(function() {
var functionName = "help";
if ($.isFunction([functionName])) {[functionName]("hello");
} else {
alert("not a function");
}
return false;
});
$('a.two').click(function() {
var functionName = "help";
if ($.isFunction(functionName)) {
functionName("hello");
} else {
alert("not a function");
}
return false;
});
$('a.three').click(function() {
var functionName = "help2";
if ($.isFunction(functionName)) {
functionName("hello");
} else {
alert("not a function");
}
return false;
});
$('a.four').click(function() {
var functionName = "help2";
if ($.isFunction([functionName])) {[functionName]("hello");
} else {
alert("not a function");
}
return false;
});
});​
As you can see, I tired a bunch of things, but all the wrong ones probably...
I inspired some of them from: jQuery - use variable as function name
Overall
I'm passing a variable that has the same name as a function, using jquery to check if it is a function, if it is, it should execute the function.
Thanks in advance for your help.

If you are wanting to call a function by a string of its name just use window.
var functionName = "help";
if ($.isFunction(window[functionName])) {
window[functionName]("hello");
} else {
alert("not a function");
}

You can use the following to invoke functions that are defined in the window/global scope, such as the function help:
if ($.isFunction(window[functionName])) {
window[functionName]("hello");
}
help2, on the other hand, is not accessible this way since you are defining it in a closure. A possibile solution is to define the function outside of the .ready() handler. Then, you can use window[functionName] to call it:
var namespace = {
help: function (var1) {
alert(var1);
},
help2: function (var1) {
alert(var1);
}
}
$(document).ready(function() {
var functionName = "help";
if ($.isFunction(namespace[functionName])) {
namespace[functionName]("hello");
}
});
DEMO.

Check Fiddle for the working example.
Example have only one link working. make other links similarly.
Edit: after first comment
HTML
<a class="one" href="#">click</a><br />
JS
var help = function(var1) {
alert(var1);
}
$(document).ready(function() {
$('a.one').click(function() {
var functionName = help;
if ($.isFunction(functionName)) {
functionName('test');
} else {
alert("not a function");
}
return false;
});
});​

Related

How to optimize this javascript duplicates

I wrote this code, but since I'm just starting to learn JS, can't figure out the best way to optimize this code. So made a duplicates for every if statement.
$(function() {
var lang = $(".lang input[type='checkbox']");
var gender = $(".gender input[type='checkbox']");
if(lang.length == lang.filter(":checked").length){
$('.lang').hide();
$('.lang-all').click(function(){
$('.lang-all').hide();
$('.lang').slideToggle(200);
});
} else {
$('.lang').show();
$('.lang-all').hide();
}
if(gender.length == gender.filter(":checked").length){
$('.gender').hide();
$('.gender-all').click(function(){
$('.gender-all').hide();
$('.gender').slideToggle(200);
});
} else {
$('.gender').show();
$('.gender-all').hide();
}
});
So this is my code, as you can see on line 15 if(gender... I have a duplicate of previous code, just changed variable from "lang" to "gender". Since I have more that two variables, I don't want to make duplicate of code for every each of them, so I hope there is a solution to optimize it.
You can write a function to let your code more abstract, see:
function isChecked(obj, jq1, jq2){
if(obj.length == obj.filter(":checked").length){
jq1.hide();
jq2.click(function(){
jq2.hide();
jq1.slideToggle(200);
});
} else {
jq1.show();
jq2.hide();
}
}
//Your jQuery code, more abstract
$(function() {
var lang = $(".lang input[type='checkbox']");
var gender = $(".gender input[type='checkbox']");
isChecked(lang, $('.lang'), $('.lang-all'));
isChecked(gender, $('.gender'), $('.gender-all'));
});
make a function which had similar functionality, then pass a parameter as a class or id
$(function() {
call('.lang');
call('.gender');
function call(langp){
var lang = $(langp+" input[type='checkbox']");
if(lang.length == lang.filter(":checked").length){
$(langp).hide();
$(langp+'-all').click(function(){
$(langp+'-all').hide();
$(langp).slideToggle(200);
});
} else {
$(langp).show();
$(langp+'-all').hide();
}
}
});

disable function using javascript

I can not seem to find the code to disable a javascript function. What I want to do is have a javascript function and then I want to disable it. Here is the code:
<script>
var fooFunc = function fooFunction() {
alert("HELLO");
};
$(document).ready(function() {
fooFunc.disable();
});
</script>
<button onclick="fooFunc()">Button</button>
Basically, when the button is click the function should not work, it should be disabled. Thanks
"Disabling" fooFunc is the same as setting it to an empty function (not to null--that will cause an error when it is called the next time). In this case:
$(document).ready(function() {
fooFunc = function() { };
});
But I don't see how this is different from simply removing the onclick handler from the HTML element.
If you want the ability to disable/re-enable the function, you can write it like this:
fooFunc = function() {
function _fooFunc() {
if (!enabled) return;
alert("HELLO");
}
var enabled = true;
_fooFunc.enable = function() { enabled = true; };
_fooFunc.disable = function() { enabled = false; };
return _fooFunc;
}();
If you want to extend this to allow any function to be enabled/disabled, you can write a higher-order function, which takes any function as a parameter, and returns a function with enable and disable methods attached to it:
function disablable(fn) {
function inner() {
if (!enabled) return;
fn();
}
var enabled = true;
inner.enable = function() { enabled = true; };
inner.disable = function() { enabled = false; };
return inner;
}
Now you can define fooFunc as
var fooFunc = disablable(function fooFunction() {
alert("HELLO");
});
and the rest of your code will work as you want.
You can access the onclick property of the element..
<button id="id" onclick="fooFunc()">Button</button>
<script>
document.querySelector('#id').onclick = '';
</script>
If you don't want the function to work at all and be totally disabled then use the below.
If you want the function to work only under certain conditions then you will need if/else statements so it will work only when the conditions that you have set are met.
$(document).ready(function(){
$("button").onclick(function(event){
event.preventDefault();
});
});
You were going to define it back to undefined or null.
fooFunc=undefined;
You Should be doing this :) Change function definition on very first run and you are good to go.
<! DOCTYPE html>
<html lang="en">
<body>
<script>
var fooFunc = function() {
alert("HELLO");
fooFunc = function(){};
};
var enablefooFunc = function()
{
fooFunc = function() {
alert("HELLO");
fooFunc = function(){};
};
}
</script>
<button onclick="fooFunc()">Run once and Disable FooFunc</button>
<button onclick="enablefooFunc()">Enable FooFunc</button>
</body>
</html>

First jquery plugin

Im trying to make my first jquery plugin.. but actually i dont know what im doing wrong here.
$(document.ready(function()
{
var plugin = (function()
{
//this function is not accessible from the outside
function privateFunction()
{
}
//these functions are
return
{
alert1: function()
{
alert('Hallo');
},
alert2: function()
{
alert("hi");
}
}
})()
//but it is not working :/
plugin.alert1();
});
it is not executing one of the alerts. Am i putting some semicolons wrong?
i checked if all were closed
Javascript's automatic semicolon insertion will add a semicolon after return and undefined is returned.
Your code will look like
return;
{...
Replace
return
{
Should be
return {
You're also missing the ) after document in the first line of code.
Demo
$(document).ready(function() {
var plugin = (function() {
//this function is not accessible from the outside
function privateFunction() {
// Code Here
}
//these functions are
return {
alert1: function() {
alert('Hallo');
},
alert2: function() {
alert("hi");
}
};
}());
//but it is not working :/
plugin.alert1();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Passing an argument to a function

Very simply I want to use the following code several times on my page for a number of 'boxes', so how can I pass an argument when it's called ie calling conceal(box1ID) would conceal box1ID and so on.....
function conceal() {
if(document.getElementById('box1ID').style.display=='block') {
document.getElementById('box1ID').style.display='none';
}
return false;
}
function show() {
if(document.getElementById('box1ID').style.display=='none') {
document.getElementById('box1ID').style.display='block';
}
return false;
}
Its very simple, just write it and include it...
function conceal(element) {
if(document.getElementById(element).style.display=='block') {
document.getElementById(element).style.display='none';
}
return false;
}
function show(element) {
if(document.getElementById(element).style.display=='none') {
document.getElementById(element).style.display='block';
}
return false;
}
Call it like so:
conceal('box1ID');
I'm not sure what you need. Is something like this?
function conceal(boxId) {
if(document.getElementById(boxId).style.display=='block') {
document.getElementById(boxId).style.display='none';
}
return false;
}
function show(boxId) {
if(document.getElementById(boxId).style.display=='none') {
document.getElementById(boxId).style.display='block';
}
return false;
}
show('box1ID');
conceal('box1ID');
You mean like this?
function conceal(boxID) {
if(document.getElementById(boxID).style.display=='block') {
document.getElementById(box1ID).style.display='none';
}
return false;
}
and
function show(boxID) {
if(document.getElementById(boxID).style.display=='none') {
document.getElementById(boxID).style.display='block';
}
return false;
}
Here I save some code
function showhide(id,show) {
document.getElementById(id).style.display=show?'block':'none';
return false;
}
usage inline (I assume you use inline due to the return false)
Show
Hide
To toggle use
function toggle(id) {
document.getElementById(id).style.display=document.getElementById(id).style.display=="block"?"none":"block";
return false;
}
usage inline (I assume you use inline due to the return false)
Toggle
<input type="Button" onclick="conceal(this.id)"/>
Javascript:
function conceal(buttonId) {
if(document.getElementById('+buttonId+').style.display=='block') {
document.getElementById('+buttonId+').style.display='none';
}
return false;
}

Javascript.. problem with value by reference possibly

The problem here is that page at alert has the final value of i.. any solution to this?
for(var i=start;i<=end;i++)
{
num=pageNumber.clone();
num.click(function(event)
{
event.preventDefault();
var page=i;
alert(page);
// drawPager();
});
num.find("span").text(i);
if(i==curPage) {
num.find("span").addClass("current");
num=num.find("span");
}
$("#pager>div").append(num);
}
You should do something like this:
num.click(function(i) {
return function(event) {
event.preventDefault();
var page = i;
alert(page);
}
}(i));
This would make an extra enclosure, so i wouldn't get overwritten.
You need to add the handler in a separate function that takes i as a parameter.
For example:
for(var i=start;i<=end;i++) {
handlePage(i);
}
function handlePage(i) {
num=pageNumber.clone();
num.click(function(event)
{
event.preventDefault();
var page=i;
alert(page);
// drawPager();
});
num.find("span").text(i);
if(i==curPage) {
num.find("span").addClass("current");
num=num.find("span");
}
$("#pager>div").append(num);
}
This way, a separate closure (with a separate i parameter) will be generated for each function call.

Categories

Resources