Change margin value on table with value from a variable with jQuery? - javascript

I select some tables using this:
$('.StatusDateTable').each(function() {
var statusLight = $(this).find(".StatusLight").attr("src");
statusLight = statusLight.substring(33).slice(0,-9);
if (statusLight == "Blue") {
var columns = Math.abs((start - end)-1);
var columnWidth = 40;
var marginRight = Math.abs(columnWidth * columns);
Now I want to set margin-right="theValueOfmarginRightHere" on the current table, is this possible?
I tried something like:
$(this).attr('margin-right=" + marginRight + "');
but obviously it doesn't work.
Thanks in advance.

$(this).css('marginRight',marginRight + 'px');

$(this).css({marginRight:marginRight})

Use .css():
$(this).css('margin-right', marginRight);
You might have to add px at the end, not sure about this: marginRight + 'px'.
Comments on your code line:
margin-right is no attribute of an HTML element. It is a CSS property. So you cannot set such properties with the attr() method.
Have a look at attr() which parameters the method expects. It is either:
attr(name) to get the attribute value.
attr(name, value) to set the value. You don't have to create a string like name=value.
When you do string concatenation, you have to be careful with mixing ' and ". Yours would indeed create the string margin-right=" + marginRight + " (as you can see from the syntax highlighter). To concatenate the right way, you have to put single quotes at the right spot:
'margin-right="' + marginRight + '"'
// --^ --^
`

Related

How can I convert the string value of a jQuery object into an actual jQuery object?

I have this string in my JS code right now:
newWords = '$(p span.word[style="--' + paraIndex + 'word-index:undefined"], p span.whitespace[style="--' + paraIndex + 'word-index:undefined"])';
I want to convert this string into a jQuery object that I can use do identify those specific elements.
I also saw the eval() function. That looks like it does what I want it to, but is super unsafe/unsecure.
Does anyone know a safe way to do this?
The simplest solution is to remove $( and ) and pass the remaining string as an argument to $():
var paraIndex = 0;
var newWords = '$(p span.word[style="--' + paraIndex
+ 'word-index:undefined"], p span.whitespace[style="--'
+ paraIndex + 'word-index:undefined"])';
var jQ = $(newWords.slice(2, -1));
console.log(jQ);
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Pure Javascript - Turn number into a %

My program spits out a number between 0 and 1, and I cant change that. I need to turn it into a % to use as a variable for a CSS selector.
<div id="Value">0.50</div>
<script>
var element = document.getElementById("Value");
var percent = element * 100;
</script>
But how am I meant to put a % symbol on the end so I can do this:
document.getElementById("circle").style.marginLeft = percent;
Any help would be appreciated, thank you.
String concatenation:
document.getElementById("circle").style.marginLeft = percent + "%";
Since "%" is a string, percent will get converted to string and then the result will be the percent value followed by "%".
As Federico pointed out, you should be using either .value (if the id="Value" element is a field element [an input, textarea, or select]) or .textContent or .innerHTML (if it's not). In your case, it's a div, so textContent would make sense:
var value = document.getElementById("Value").textContent;
var percent = value * 100; // Implicitly converts `value` to number
document.getElementById("circle").style.marginLeft = percent + "%"; // Implicitly converts `percent` to string
try
circle.style.marginLeft = Value.innerText*100 + '%'
<div id="Value">0.50</div>
<div id="circle">◉<div>
document.getElementById("circle").style.marginLeft = percent + '%';
When used on strings, the + operator is called the concatenation operator.
Reference: Javascript Operators
This should solve it.
document.getElementById("circle").style.marginLeft = percent+"%";
In Javascript you can concat natively an int and a string using the '+' operator which means that -
var a = 5
var b = a + '%'
result is b = '5%'
Use innerHTML to get the text from the element
var element = document.getElementById("Value").innerHTML;
var percent = parseFloat(element)*100;
percent+='%';
console.log(percent)
<div id="Value">0.50</div>

Setting font-size with random value using jQuery?

When returning a fixed value, font-size is changing fine:
$wordElement.css('font-size', function() {
return '3vw';
});
But when trying to return a random value like this:
$wordElement.css('font-size', function() {
return '\'' + Math.ceil((cssRandom * 3) + 1) + 'vw\'';
});
It does not work.
What's wrong here? And how do I set font-size to random value?
Remove unnecessary escape and quotes surrounding Math.ceil call. You can use $.now() .slice() to retrieve a "random" numeric value
var cssRandom = String($.now()).slice(-1);
$("div").css("font-size", function() {
return Math.ceil((cssRandom * 3) + 1) + "vw";
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>abc</div>
I don't think cssRandom is javascript.
Try
Math.ceil((Math.random() *3 )+1)

Optimizing syntax for modifying a CSS value with jQuery using math

I've got a jQuery function to modify the width values of two CSS classes. The width is given in percentage for both classes. As written, it works, but I'm trying to optimize my jQuery code so it works with just variables. Here is the relevant code (percent is an earlier defined variable):
$('.eventdescription').css({width : 75 - percent + '%'});
$('.function').css({width : 25 + percent + '%'});
I'm trying to get rid of the '75' and '25' values. I've tried the following:
$('.eventdescription').css({width : -=percent + '%'});
$('.function').css({width : +=percent + '%'});
But I get an 'unexpected identifier' error. Enclosing '+=percent' and '-=percent' in quotes doesn't seem to do anything. What am I doing wrong?
Thanks for reading.
EDIT: See Tom Chung's answer. The correct syntax is enclosing the += and -= operators in quotes and including them as discrete units in the operation.
$('.eventdescription').css({width : '-=' + percent + '%'});
$('.function').css({width : '+=' + percent + '%'});
'-=' && '+=' operator should be in form of string.
Further explaining, the code +=percent is invalid. Proper usage of it should be,
var originalPercent = 0;
originalPercent += percent;
// Now, value of originalPercent will be originalPercent + percent

need to extract certain values from attribute and place them in variables

In the following markup on a page I want to extract out the following and put them in seperate variables.
1- In the onclick attribute get the value after the "ProductID" and put it in its own variable. "ProductID"
So in this case it would be 318
2- In the onclick attribute get the value after the "Orig_price" and put it in a variable, "Orig_Price" So in this case it would be 22.95
3- In the onclick attribute get the value after the "width" and put it in a variable, "width" So in this case it would be 330
4- In the onclick attribute get the value after the "height" and put it in a variable, "height" So in this case it would be 300
<img src="/v/vspfiles/templates/100/images/buttons/btn_quantitydiscounts.gif" border="0" align="absmiddle">
UPDATED DEMO:
DEMO: http://jsbin.com/axuce3/3 SOURCE: http://jsbin.com/axuce3/3/edit
var pieces = $('a').attr('onclick').toString().split('?')[1].split('=');
var parts = [];
for (var i = 0; i < pieces.length; i++) {
var value = parseFloat(pieces[i]);
if (!isNaN(value)) parts.push(value);
}
alert( 'ProductID=' + parts[0] + 'Orig_price=' + parts[1] + 'width=' + parts[2] + 'height=' + parts[3]);
Please forget my previous answer, it was wrong (to test it, I assigned an id to the wrong element). You can get the value of the onclick attribute using getAttribute. For testing purposes, I changed your example to
<img src="/v/vspfiles/templates/100/images/buttons/btn_quantitydiscounts.gif" border="0" align="absmiddle">
Now document.getElementById("test").getAttribute("onclick") returns
window.open('/BulkDiscounts.asp?ProductID=318&ProductCode=' + escape('LB30X40ES') + '&Orig_Price=22.95', 'Discounts', 'scrollbars,status,resizable,width=330,height=300');
Now you can get the values using
var theString = document.getElementById("test").getAttribute("onclick");
var ProductID = theString.match(/ProductID=(\d*)/i)[1];
var Orig_Price = theString.match(/Orig_price=([\d\.]*)/i)[1];
var width = theString.match(/width=(\d*)/i)[1];
var height = theString.match(/height=(\d*)/i)[1];
(code is stolen from Tambourine's answer, so please give him the credits ;).
Try this code:
var string = $('a').attr('onclick') + ""; // to be sure var string is string
ProductID = string.match(/ProductID=(\d*)/i)[1];
Orig_Price = string.match(/Orig_price=([\d\.]*)/i)[1];
width = string.match(/width=(\d*)/i)[1];
height = string.match(/height=(\d*)/i)[1];

Categories

Resources