How do I run a function from a variable? - javascript

I'm trying to run a function from a variable I've defined although it's not working.
Here is an example of what I mean:
$(document).ready(function(){
function red () {
alert("You chose the color red");
}
function blue () {
alert("You chose the color blue");
}
$(window).resize(function() {
var colorvalue = "blue" + "();";
return colorvalue
});
});
If someone could correct my faulty logic that would be helpful, thanks.
SOLVED! FULL SOLUTION HERE
function red () {
alert("You chose the color red");
}
function blue () {
alert("You chose the color blue");
}
$(document).ready(function(){
$(window).resize(function() {
var colorvalue = "blue";
var callable = window[colourvalue];
callable();
});
});

The following code will work absolutely
$(window).resize(function() {
var callable = window["blue"];
callable();
});
Try it

Try this:
var red = function{ alert("You chose the color red"); };
var blue = function{ alert("You chose the color blue"); };
$(document).ready(function(){
$(window).resize(function() {
var colorvalue = window["blue"];
return colorvalue();
});
});
This way you can evaluate the target function to call without using eval.

you should try
return eval(colorvalue);

Set up an object with your functions as methods. (This avoids multiple globals.)
var colour = {
red: function{ ... },
blue: function{ ... }
}
Then call colour[myOption] where myOption is set to be "blue" or "red" somehow (probably by the user).

Put your function out of you Document ready function. like below
function red() {
alert("You chose the color red");
}
function blue() {
alert("You chose the color blue");
}
$(document).ready(function () {
$(window).resize(function () {
var colorvalue = "blue" + "();";
return eval(colorvalue);
});
});
if you want to use in document ready then use like onclick to particular id : exp: $( "#target" ).click();
REF

Just do:
var colorvalue = blue;
return colorvalue();
Though note that the alert() function doesn't return anything, and your functions aren't even returning anything, so right now your functions will return undefined. Perhaps you meant to define them like:
function blue () {
var msg = "You chose the color blue";
alert(msg);
return msg;
}

you could try:
var red = function(){
// doSomething
}
var blue = function(){
//doSomething
}

Related

Clear html spaces in jQuery

I am beginner webdeveloper.
I have this function:
function showRalColors() {
const getHex = ral => rals[ral];
$(".ral").each(function () {
var color = $(this).data("id");
$(this).css('background-color', getHex(color));
});
$("div.material-thumb.mini-specialColorDiv.ral").each(function () {
var color = $(this).html();
if (color != undefined) {
console.log(1);
$(this).css('background-color', getHex(color));
$(this).html(' ' + color);
}
});
}
This function work fine. The problem is with " ". Always when I run this function, I have additional " " (5x nbsp). I need MAX 5
How can I repair it?
Please help me?
Actually the codes you are using is generating spaces itself so simply remove and use like below:
$(this).html(color);
and for sapcing use
$(this).css('padding-left', '5px');

jQuery - Detect value change which use .val() function

We all know that use the val() will not trigger the change event, so we also use .trigger('change') behind the val().
But the problem is that someone write the val() did't with trigger() and it's a external file that I can't edit it.
So, how can I detect value change through some code same like below:
$('.elem').on('change', function(){
// do something
});
My suggestion is to override jquery's val()
var originalValFn = jQuery.fn.val;
jQuery.fn.val = function() {
this.trigger('change');
originalValFn.apply( this, arguments );
}
jsfiddle: http://jsfiddle.net/2L7hohjz/js
var originalValFn = jQuery.fn.val;
function getErrorObject(){
try { throw Error('') } catch(err) { return err; }
}
jQuery.fn.val = function() {
if ($(this).hasClass( "element" )) {
var err = getErrorObject();
var caller_line = err.stack.split("\n")[4];
var index = caller_line.indexOf("at ");
var clean = caller_line.slice(index+2, caller_line.length);
console.log(clean);
console.log(arguments);
}
originalValFn.apply( this, arguments );
};
Try:
setTimeout(function() {
if (currentValue != previousValue)
{
// do something
}
}, 500);
Thank you,
I commonly use the solution from this post to get around problems like this one:
hidden input change event
watchField('.elem', function(){
//do some stuff here
});
function watchField(selector, callback) {
var input = $(selector);
var oldvalue = input.val();
setInterval(function(){
if (input.val()!=oldvalue){
oldvalue = input.val();
callback();
}
}, 100);
}
Try:
$('.elem').on('keyUp', function(){
// do something
});
or
$('.elem').on('lostFocus', function(){
// do something
});
Thank you,

My function is not running in JavaScript

How do I get this code to work in the "head" tag of the HTML. I must use these two functions, and cannot use only one function. I know this is bad practice, but how would I go about doing this? Thank you for your help.
var myImage;
function prepareEventHandlers() {
var myImage = document.getElementById('mainImage');
}
function runEvents() {
myImage.onclick = function() {
alert('You clicked on the image.');
};
}
window.onload = function() {
prepareEventHandlers();
runEvents();
}
You need to remove var in prepareEventHandlers(), because you are declaring a new local variable called myImage, not assigning the outer one.
var myImage;
function prepareEventHandlers() {
myImage = document.getElementById('mainImage');
}
Remove the "var" in your prepareEventHandlers() function.
var myImage;
function prepareEventHandlers() {
myImage = document.getElementById('mainImage');
}
function runEvents() {
myImage.onclick = function() {
alert('You clicked on the image.');
};
}
window.onload = function() {
prepareEventHandlers();
runEvents();
}

Jquery child div selection

I'm using switchy http://lou.github.io/switchy/ and it uses animate-color.js
I have more than one, unlike their page, everytime one gets toogle all of them turn green, how can I prevent this so one gets toogle only
$(function () {
$('.binary').switchy();
$('.binary').on('change', function () {
// Animate Switchy Bar background color 7cb15b
var bgColor = '#ebebeb';
if ($(this).val() == '1') {
bgColor = '#7cb15b';
} else if ($(this).val() == '0;') {
bgColor = '#ebebeb';
}
$('.switchy-bar').animate({
backgroundColor: bgColor
});
// Display action in console
var log = 'Selected value is "' + $(this).val() + '"';
$('#console').html(log).hide().fadeIn();
});
});
You can see what I mean here www.niors.com
Here:
$('.switchy-bar').animate({
backgroundColor: bgColor
});
you get ALL switchy-bar from document. So you need to find context you need, i.a. this way:
$(this).parent().find('.switchy-bar').animate({
backgroundColor: bgColor
});
#(this) -> select
$(this).parent() -> wrapper (.field)
and then search for switchy bar for changed select.
Of course, for better performance and readibility it'd be great to cache $(this) in some variable at the beginning of callback function.
Something like this:
$(function () {
$('.binary').switchy();
$('.binary').on('change', function () {
var $select = $(this);
var selectedValue = $select.val();
// Animate Switchy Bar background color 7cb15b
var bgColor = {
'0': '#ebebeb',
'1': '#7cb15b'
};
$select.parent().find('.switchy-bar').animate({
backgroundColor: bgColor[ selectedValue ]
});
// Display action in console
var log = 'Selected value is "' + selectedValue + '"';
$('#console').html(log).hide().fadeIn();
});
});
change
$('.switchy-bar').animate({
backgroundColor: bgColor
});
to
$(this).parent().find('.switchy-bar').animate({
backgroundColor: bgColor
});
the idea is to just change one switchy-bar which is related to element you are clicking or selecting for...

Select random function

I have a list of functions:
function randomiseiconscycle1() {
$("#iconTwoContainer img, #iconFiveContainer img, #iconSevenContainer img").fadeIn(300);
setTimeout( function(){
$("#iconTwoContainer img, #iconFiveContainer img, #iconSevenContainer img").fadeOut(300);
},200);
function randomiseiconscycle2() {
$("#iconOneContainer img, #iconSixContainer img").fadeIn(300);
setTimeout( function(){
$("#iconOneContainer img, #iconSixContainer img").fadeOut(300);
},200);
}
everytime i click this button i have i want to activate one of the 8 functions (like above) randomly.
any help would be much appreicated.
Put references to the functions in an array:
var iconcycle = [
randomiseiconscycle1, randomiseiconscycle2,
randomiseiconscycle3, randomiseiconscycle4,
randomiseiconscycle5, randomiseiconscycle6,
randomiseiconscycle7, randomiseiconscycle8
];
Now you can pick one at random and call it:
iconcycle[Math.floor(Math.random() * iconcycle.length)]();
in javascript functions are just objects, so you can do some fun things with them (such as selecting one at random)
This should be enough to get you started:
http://jsfiddle.net/jvGkp/
var arrayOfFuncs = [];
arrayOfFuncs.push(function () { alert('first func!'); });
arrayOfFuncs.push(function () { alert('second func!'); });
arrayOfFuncs.push(function () { alert('third func!'); });
arrayOfFuncs[0]();
I think you're looking for something like this...
function callRandomFunction() {
var random = Math.floor(Math.random()*8);
switch(random){
case 0:
randomiseiconscycle1();
break;
case 1:
....
...
}
}
You can create an array of functions, generate a random number and use that to call one of those functions:
http://jsfiddle.net/4PfAC/1/
Assumed that you have 2 functions i.e. randomiseiconscycle1 and randomiseiconscycle2
$(function(){
var totalfunc=2; // if more than 2 functions than increase the number.
function randomiseiconscycle1() {
var name=arguments.callee.name;
alert(name);
setTimeout( function(){
alert(name);
},200);
}
function randomiseiconscycle2() {
var name=arguments.callee.name;
alert(name);
setTimeout( function(){
alert(name);
},200);
}
$('button').on('click', function(){
var randomnumber=Math.floor(Math.random()*totalfunc+(1));
var func="randomiseiconscycle"+randomnumber;
eval(func)();
});
});​
A fiddle is here.

Categories