Applying a variable to an element's style property with js - javascript

Sorry if this question has already been asked. If so, could someone please direct me to the thread(s)? I have not found any existing ones so far.
But my question revolves around this type of action:
var Product_Linky = document.getElementById("Product_Link_Container");
Product_Linky.style.position.left= 12px;
A literal is being applied to the attribute with the indicated units. But...can a variable be applied and if so, how would the units be specified?
The following code is not written properly, but it shows an example of the problem I have:
var Product_Linky = document.getElementById("Product_Link_Container");
Product_Linky.style.position.left= 'MyVariable_x'px ;
If a variable can be used, what is the correct syntax to include the units?
Best regards!

There's a similar question already, but to answer your question this will work:
var variable_Length = 5;
var Product_Linky = document.getElementById("Product_Link_Container");
Product_Linky.style.position.left= variable_Length + 'px' ;

Try using template Literals!
In JavaScript, if you want to make a variable "fit in" to a string, you an use the following syntax:
var num = 12;
var myString = `My number is ${num}.`;
console.log(myString);
will log
My number is 12.
One important note on this: you cannot use regular quotation marks to enclose the string. You must use the backtick:
`
(it should be right above your tab key). Otherwise, this will not work.
For more information, check out the MDN Web Docs!
For an example, check out this Codepen I made! (Try changing the myHeight variable's value.)
I hope that helps!

Do this, my friend. It's called ES6 template literal
Product_Linky.style.position.left= `${MyVariable_x}px` ;
Or you do the String concatenation like this
Product_Linky.style.position.left= MyVariable_x + 'px' ;

Related

Unable to get value of JavaScript Object [duplicate]

I'm looking for an easy way to assign to a variable depending on the value of another variable.
device.slot2_clipList[clipNumber] = singleClipDetails;
what I'm trying to do is: replace the "2" with another variable, so that i can run the same operation while just changing the
var slotNumber, and write to the corresponding variable.
i tried
device.slot + device.slotNumber + _clipList[clipNumber]
but (obviously?), this doesn't work.
How can this be done? (Maybe I named the Question incorrectly, but that was the closest I could think of.)
Thanks
This is what bracket notation is for
var i = 2;
device['slot' + i + '_clipList'][clipNumber] = singleClipDetails;
device['slotNumber' + _clipList[clipNumber] ]
Explanation:
foo.bar in javascript is identical (even in performance) to foo['bar']. So any object property name can be built up from strings.

escaping a JS reserved word (already double encapsulated)

I have a JS function which is generated by some PHP, the function call is below:
onClick=openPopup('".$row['imgname']."','".$row['adtitle']."','".$row['adviews']."')
Now this works unless the value of $row['adtitle'] contains a JS keyword. The one that brought the bug in my code to my attention was the word 'THIS'. Would there be a way to escape these values, I can't figure it out as I have already used a lot of encapsulation in this call.
Thanks in advance.
EDIT:
openPopup('efc86f7223790e91f423ef1b73278435.jpg','THIS IS A TEST ADVERT 12345678','2')
This call does not work.
openPopup('eada91a6c1197d2f2320e59f45d8ca6b.jpg','is a test','2')
however this one does work..
only thing I could figure was the THIS as when looking at the source, the text following THIS is highlighed differently.
Edit 2 : Here is my function:
function openPopup(imgname,adtitle,adviews) {
document.getElementById('popup').style.display = 'block';
document.getElementById('delimg').src = 'imgstore/' + imgname;
document.getElementById('delAdTitle').innerHTML = adtitle;
document.getElementById('delAdViews').innerHTML = adviews;
document.getElementById('confirm').onclick = function() {
location.href = '?delete=1&id=' + imgname;
}
}
Maybe it’s just a question of proper formatting:
$onclick = 'openPopup('.json_encode($row['imgname']).','.json_encode($row['adtitle']).','.json_encode($row['adviews']).')';
echo 'onClick="'.htmlspecialchars($onclick).'"';
Note that we’re abusing json_encode here to quote the JavaScript string literals. Although we shouldn’t as strictly speaking JSON strings are not a subset of JavaScript strings.

Replace Word Within Word - Javascript

I need to get a id from a html element and replace a part of the word. For example:
HTML
<input type="checkbox" id="facebookCheckbox"></div>
JavaScript
var x = document.getElementById("facebookCheckbox");
var name = x.id;
name.replace("Checkbox","");
This obviously does not work because the replacing word has to be standalone for it to be replaced. Is there a different way of doing this?
I'm looking for purely javascript no jQuery
Thank you!
name.replace("Checkbox","");
This obviously does not work because the replacing word has to be standalone for it to be replaced.
No, it does work and there's no need to be "standalone" - any part of the string can be matched. Only you did nothing with the result of the operation:
console.log(name.replace("Checkbox",""));
// or
name = name.replace("Checkbox","");
// or assign back to x.id maybe?
You are creating a copy of string when replacing, so you must assign the result of .replace() back to x.id.
var x = document.getElementById("facebookCheckbox");
x.id = x.id.replace("Checkbox","");
this is not going to work in this way. However you can have a marker kind of character by which you can break the name into array and implement the logic. For example:
var x = document.getElementById("facebook_Checkbox");
//Note I have added underscore in the Id
var name = x.id;
var arr=name.split("_");
//Now you have Checkbox and Facebook as string objects (part of array) and you can use them
name=arr[0]
I hope it will solve the purpose.

Regular Expression in indexOf on javascript

I want get my program parameters from rel attribute of element, first of all is it logical ?
and the rel attribute may contain this string rel="_p|b|w=300|h=200" or rel="_p|w=300"
, so I use split to split my string with | pattern :
var attr = $(this).attr('rel').split('|');
for _p and b there is no problem because I can check with indexOf but for w and h I should use regular expression because the w and h value will be change.
how can I use regular expression in indexOf ?
sorry for my bad English
EDIT:
if (attr.indexOf('b')) {
blank = true;
}
First of all, that isn't a very elegant way of retrieving data. Anyway, if you really want to do that in that way, then you can use regexes as follows:
var matches = $(this).attr('rel').match(/w=(\d+)/);
var w = (matches && matches[1]) || defaultValue;
Also, if there can be multiple elements that end in 'w', then you'd better change your regex to something like:
var matches = $(this).attr('rel').match(/(?:^|\|)w=(\d+)/);
I would have suggested the use of custom attributes as well, however these would not be w3-conform as you want them to.
A simple way would be to split the parameters and then loop through and check each index whether it is one of the attributes you are expecting:
var cust_params = $(this).attr('rel').split('|'); //or this.rel as GGG suggested in a comment?
for(var i=0;i<cust_params.length;i++) {
if('_p'==cust_params[i]) {
//...
}
//...
if(cust_params[i].match(/w=(\d+)/)) {
//you could even do this without a regular expression
}
}
I hope this doesn't violate some good practice that I'm unaware of because I always feel like there must be a more elegant way when I do this kind of thing :) As it is I get a kind of quick-and-dirty feel about this.
Sorry there is no way you can do it in one command with normal javascript, indexOf just doesn't support regular expression.
You can either loop through the array or use jquery supported command for array.
For example: once you have the array attr as you like, you can use jQuery.grep() http://api.jquery.com/jQuery.grep/
a_equal = jQuery.grep(attr, function(a, i){
return (a.match(/=/) and i > 0); // modify this as you like
});
to create an array a_equal with all the assignment argument.
disclaimer.. code not yet tested.
Like Paolo Bergantino I'd also suggest using data-attributes, or you could store the data in a JSON (again, in a data attribute) and parse that:
<a href="#" data-info='{"width": "300", "height": "200", "color": "#fff", "etc": "foo"}'>
var info = JSON.parse(a.getAttribute('data-info'));
Edit: replaced eval with Phrogz's suggestion.
(With eval: eval('(' + a.getAttribute('data-info') + ')'))

Quotes in Javascript

I have been trying for hours to fix this code, I can't see what's wrong:
document.getElementById('detail'+num).innerHTML='<a class="dobpicker" href="javascript:NewCal('+s_d+','+ddmmyy+')">'
The problem is in href="javascript ..."
s_d is a javascript variable defined as
var num = 2;
var s_d = "sname"+num;
var ddmmyy = "ddmmyy";
Basically I need to call a javascript function with different parameter each time.
Use a backslash like \'.
document.getElementById('detail'+num).innerHTML=
'<a class="dobpicker" href="javascript:NewCal(\''+s_d+'\',\''+ddmmyy+'\')">'
Since this is the value of a href attribute, HTML encode them:
document.getElementById('detail'+num).innerHTML='<a class="dobpicker" href="javascript:NewCal("'+s_d+'","'+ddmmyy+'")">'
Or better yet don't use the javascript: protocol:
[0,1,2,3,4,5].forEach(function(num) {
var s_r = "sname"+num;
var ddmmyy = "ddmmyy";
var aEl = document.createElement("a");
aEl.className = "dobpicker";
aEl.onclick = function() {
NewCal(s_d, ddmmyy);
}
document.getElementById('detail'+num).appendChild(aEl);
});
Your .innerHTML setting is using s_d, but your variable declaration has s_r.
EDIT: That was the first thing that jumped out at me. Having looked a bit closer and realised the values are strings, I think fixing the variable name together with adding some escaped quotation marks as in Daniel A. White's answer will do the trick.

Categories

Resources