Can I use a string variable in document.getElementById()? - javascript

here is my code:
function figureSelector () {
document.getElementById("rook").onclick = function () {
curr = '"rook"';
};
};
function moveLine(){
document.getElementById("upButton").onclick = function() {
document.getElementById(curr).style.top = document.getElementById(curr).offsetTop - getPix() * 62 + "px";
counter= counter + getPix();
};
I want to write an universal function for a chess piece to move. All I want is, when one clicks the chess piece, and then presses the up button, it must go up.

Yes you can use String variable:
HTML:
<div id="name" style="width:300px;height:300px;background:red"></div>
javascript:
var b = 'name';
document.getElementById(b).innerHTML = 'none';
jsfiddle here

Yes, you can.
Just use
curr = 'rook';
(without the extra quotes)

You can even do stuff like this:
function mark(yy) {
for (var ii = 0; ii < 7; ii++ ) {
if ( ii == yy ) {
document.getElementById("b"+ii).style.fontWeight = "bold";
}
...
But be careful of your loop limits to be sure you have a matching id. I just spent hours trying to figure out why ("b"+ii) was getting error and finally realized that the error was being caused by exactly that. duh...

Yes, Mate, you can.
You can use a variable as the argument for any function. That's just how functions work -- they don't care where the argument comes from. You should define curr outside those functions.

Related

create a new variable automaticaly

This is a general question. But an answer in JavaScript would suit me the best.
I'm searching for a way to create variables after a pattern automatically.
For example, I want to create a while-loop in which a variable gets declared. In set loop, I want to create the variable car1. However, in the next loop pass I want to do the same thing BUT call the Variable car2 this time.
I'll try to write it in pseudocode:
//this should happen in the first loop
while(true){
var car1 = 1 + 2;
console.log(car1)
}
//this should happen in the second loop
while(true){
var car2 = 1 + 2;
console.log(car)
}
//In both cases "3" should be the output. But different Variables
Contrary to this example. I want to do all this in a single while loop. And on every while loop, a new variable should be created. So car1,car2,car3,car4.
Thanks in advance!
Maybe you can use an array and add an item every loop iteration or a hash map with a naming convention you set for the keys
You can try to use globalThis or window.
function nameFunction(name, f) {
return {
[name](...args) {
return f(...args)
}
}[name]
}
// use globalThis
for (let i = 1; i <= 3; i++) {
const funcName = `car${i}`;
const func =
nameFunction(funcName, () => console.log(`this is car ${i}`));
globalThis[funcName] = func;
}
car1(); car2(); car3();
// use window
for (let i = 4; i <= 6; i++) {
const funcName = `car${i}`;
const func =
nameFunction(funcName, () => console.log(`this is car ${i}`));
window[funcName] = func;
}
car4(); car5(); car6();
I hope this link will help you with this problem.
JS Dynamic Variable
Here they have discussed 2 ways of solving the problem. (One with "eval" and the other with "windows" object.

appendChild with onclick function that passes through the div's value

Good day everyone,
I've been grinding the whole day yesterday at this function however I've been running in circles and would
appreciate any input or suggestions.
Currently I want to create a onclick function on my div (match-tab) that when it gets clicked it will send it's value to my javascript which will let the function know which game's data it should render.
at the moment my function looks like this:
for (x in data){
var recent_matches_row_one = document.getElementById('recent-matches-row-one');
var recent_matches_row_two = document.getElementById('recent-matches-row-two');
var col = document.createElement("div");
col.className = "col no-padding";
var matchTab = document.createElement("div");
matchTab.className = "match-tab";
matchTab.id = "match-tab";
matchTab.value = x;
matchTab.innerHTML = ++x;
matchTab.onclick = foo(this.value);
if (x < 15){
recent_matches_row_one.appendChild(col);
col.appendChild(matchTab);
} else if (x > 15) {
recent_matches_row_two.appendChild(col);
col.appendChild(matchTab);
}
}
}
function foo(value){
var v = value;
console.log(v);
}
As you can see the recent matches functions renders the amount of match tabs according to the amount of match data available.
The front end looks like this and as you can see it is seen as undefined.
I would really like to write this whole application in vanilla JavaScript since I'm new to it and want to learn it before moving to other frameworks and libraries.
Thanks
So the answer to my question was is the fact that I had to change matchTab.onclick = foo(x); to matchTab.onclick = function(){foo(this.value)}; this allowed me to get the value assigned in my JavaScript. Thanks for all the input!

Creating a new function that takes default arguments for another function (Javascript)

I am currently trying to create a defaultArguments function that takes in a function and some parameters that are set as default values. The steps I am thinking about taking to solve this particular problem is to:
Parse through the function in order to obtain what its arguments which could be anything.
Go through each argument that was extracted and replace arguments that have input parameters to its respective value.
Now, what I was thinking about doing next was to add additional default arguments into the input 'func'. I tried to:
Look up how to input a string as an argument into an existing function. However, the function then just reads the argument string as just a string.
Use the JavaScript .apply method. However, I won't always have all input values.
Here is the code I wrote so far.
function defaultArguments(func, params) {
var reg = /\(([\s\S]*?)\)/;
var extractVar = reg.exec(func);
if (extractVar) {
var arguments = extractVar[1].split(',');
}
for (i = 0; i < arguments.length; i++) {
if (params[arguments[i]]) {
arguments[i] = params[arguments[i]];
}
}
}
So for example, if I have a function
function add(a,b) { return a+b; };
I would use the defaultArguments function as such
var add_ = defaultArguments(add,{b:9});
console.log(add_(10) === 19); // b is defaulted to 9
console.log(add_(10,7) === 17); // b is given so use given value
console.log(add_()); // NaN
I would love some hints as to how to solve this problem and a different approach if I am approaching this problem incorrectly. I appreciate your time for reading this and I hope to see your response!
UPDATE:
So I was able to come up with a rough solution for this question. I was wondering if I approached the problem correctly and if there's any improvements do to my code. After researching a lot, I know that I shouldn't use eval(), but I don't know how else to tackle the problem. I am open to suggestions. Thanks in advance!
function defaultArguments(func, params) {
var stringed = func.toString();
var inputs = stringed.match(/\(.+\)/)[0].replace("(", "").replace(")", "").split(",")
for (i = 0; i < inputs.length; i++) {
inputs[i] = ""+inputs[i]+" = "+inputs[i]+" || "+params[inputs[i]]+";"
}
for (i = 0; i < inputs.length; i ++) {
stringed = stringed.replace("{", "{ "+inputs[i]+"")
}
var newFunc = "var restoreFunc = " + stringed;
eval(newFunc);
return restoreFunc;
}

Create variables on the fly

Im creating code snippets dynamicly:
var gg = setInterval(function() {
if($('p:visible').length > 0) {
$('p').trigger('click') ;
clearInterval(gg);
}
},500);
The code works. The problem is that I create the same code snippets with different selectors:
var gg = setInterval(function() {
if($('input:visible').length > 0) {
$('input').trigger('focus') ;
clearInterval(gg);
}
},500);
So when I put(create) these codes together, the whole thing goes in to some loop and it doesn't work anymore, take a look at this example: JsFiddle
The problem is that I assign the same variable (gg) to the codes. So my question is: How do I create different variables every time I create these code snippets? I tried some things with var x=x++ but I can't get it to work.
Here are two ways of accomplishing what you want to do (dynamic variables). The first is evaling a string.
(There are a ton of articles out there that will explain why this is bad. But, for the sake of being complete, I'm providing this example...maybe as an example of what not to do ;)
A function that creates variables based on a string you pass in, and then using that eval'd variable would work. Something like:
function varMaker(str){
// Nothing fancy...
var token = Math.floor(new Date().getTime() * Math.random(10));
// Defining variable with no var for global scope (bad)
return eval(str + '_' + token + ' = undefined;');
}
Here's a quick/dirty fiddle example (no function maker, just an eval'd string): http://jsfiddle.net/D3wZ7/
The second, cleaner approach is using square bracket notation (and what I would recommend). Something like this:
window['gg' + randomized_string] = setInterval(..)
Note: Once you've defined the variable, you can reference it as you normally would as such:
window['my_cool_variable' + 1] = "stack";
alert(my_cool_variable1); //alerts "stack"
Here's a fiddle demonstrating this: http://jsfiddle.net/ZmGH5/
Good luck!
Simply put the snippets in anonym wrapper functions so that the variable gg is not global anymore:
(function(){
var gg = setInterval(function() {
if($('input:visible').length > 0) {
$('input').trigger('focus') ;
clearInterval(gg);
}
},500);
})();
(function(){
var gg = setInterval(function() {
if($('p:visible').length > 0) {
$('p').trigger('click') ;
clearInterval(gg);
}
},500);
})();
(These Functions are executed automatically...)
var gg= [];
gg[0] = setInterval(function() {
if($('p:visible').length > 0) {
$('p').trigger('click') ;
clearInterval(gg[0]);
}
},500);
gg[1] = setInterval(function() {
if($('input:visible').length > 0) {
$('input').trigger('focus') ;
clearInterval(gg[1]);
}
},500);
so go on like this way. You can create lots of by using array.
in that other snippet change
var gg =...
to var hh =...
and then clearInterval(hh)

JQuery for loop

I need to Loop in JQuery from 0 to variable-value(dynamically entered by user).How can i achieve this?
Now i am doing it by using simple For loop like this.
for( i=1; i<=fetch; i++) {
var dyndivtext = document.createElement("input");
document.body.appendChild(dyndivtext);
}
Thanks.
You could loop an empty array:
$.each(new Array(fetch), function(i) {
var dyndivtext = document.createElement("input");
document.body.appendChild(dyndivtext);
});
If you do this alot you can even fake-patch jQuery.each to take numbers:
(function($) {
var _each = $.each;
$.each = function() {
var args = $.makeArray(arguments);
if ( args.length == 2 && typeof args[0] == 'number') {
return _each.call(this, new Array(args[0]), args[1]);
}
return _each.call(this, args);
};
}(jQuery));​
$.each(fetch, function(i) {
// loop
});
jQuery.each does have some great features, like the different return values inside the callback. But for a simple loop I find it much more convenient (and less overhead) to do something like:
while(fetch--) {
// loop
}​
To loop between two values you should use a regular Javascript loop. The jQuery each methods are used when looping through a collection of elements or an array.
To loop from zero, you should initialise the loop variable to zero, not one. To loop from zero to the specified value, you use the <= for the comparison, but to loop from zero and the number of items as specified (i.e. from 0 to value-1), you use the < operator.
for (i = 0; i < fetch; i++) {
$('body').append($('<input/>', { type: 'text' }));
}
You mean Javascript loop.
From W3Schools:
for (var variable = startvalue; variable < endvalue; variable = variable + increment)
{
//code to be executed
}
To get the value from user and run the code you can use the following prompt.
var x=prompt("Enter the value",0);
for(i=0;i<x;i++)
{
var dyndivtext = document.createElement("input");
document.body.appendChild(dyndivtext);
}
Hope this helps.
Thanks
If you want it the full jQuery way then use that new plugin jQuery-timing. It provides inline-loops in your jQuery line:
$('body').repeat().append('<input>').until(fetch);
Nice, eh?

Categories