Optimizing syntax for modifying a CSS value with jQuery using math - javascript

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

Related

JavaScript Math Expression Yields Different Results

The following is a line I have in my Javascript code. It outputs -5108024 and some change when sqftVal = 2828 and bathsVal = 3.5.
out.value = -6932000 + 221400 * Math.log(sqftVal) + 637.2*Math.exp(bathsVal) + 51640;
However, when I manually type this in my calculator, I get roughly -5099721 and some change. I get the same result in R. Why does JavaScript mess up the math, and what can I do to fix this?
Calculator/R input:
-6932000 + 221400 * ln(2828) + 637.2 * e^(3.5) + 51640 = -5099721.073
I don't believe this is a floating point error because as I add more terms, the difference becomes fairly large.
Plus, everything was matching up until I added the fourth term (+51640) which made no sense to me.
There must be some other code that is interfering with your values or something, because the code shown does not produce the value you report.
var sqftVal = 2828;
var bathsVal = 3.5;
var value = -6932000 + 221400 * Math.log(sqftVal) + 637.2*Math.exp(bathsVal) + 51640;
console.log(value);

Preventing jQuery from using Scientific Notation in $.Animate()?

How am I able to prevent jQuery from using scientific notation - 1.2e+07 instead of 12,000,000 within the jQuery.animate() function?
Using: $('body').css({ backgroundPositionX: 12000000 + 'px' });
Converts to: background-position-x: 1.2e+07px;
Desired results: background-position-x: 12000000px;
This starts occuring as soon as the number hits 1 million (1,000,000):
This, in turn, causes my application to behave strangely. I want pure, simple integer numbers -- none of this scientific nonsense! I've looked around but I cannot find anything related to the jQuery library. Only pure JS functions.
Note 1: It's not just animate, but $.css() as well. I assume other jQuery functions are similar also.
Note 2: I don't think it's the browser that does it because if I enter the value in manually it works just fine until you hit the usual max 32 bit integer
Why is this a problem:
12000321 converts to: 1.20003e+07
When I then convert 1.20003e+07 back to an integer I get: 12000300
When you get to Scientific Notation, the step size is in the 100s & not 1s and not specific enough.
Thank you for considering my question
Wow... took me a long time but I finally managed to work out a way of doing this.
After lots of testing I noticed that passing a direct string to $.attr() did not convert the numbers to the scientific notation.
I created a custom animation and manually set the style attribute as a string.
Seems to be working & going up in single digits not 100s!!
$({
x: this.x,
y: this.y
}).animate({
x: x,
y: y
}, {
easing: this.motion_type,
duration: this.duration,
step: function(now, fx) {
var current_styles = $('.area').attr('style'),
current_styles = string = current_styles.split(" ");
var x = parseFloat(current_styles[1].replace('px', '').replace(';', ''));
var y = parseFloat(current_styles[2].replace('px', '').replace(';', ''));
if ('x' === fx.prop) {
x = now;
} else if ('y' === fx.prop) {
y = now;
}
$('.area').attr({ style: 'background-position: ' + x + 'px ' + y + 'px;' });
},
complete: function() {
t.stopNow();
}
});

display pointlabel in highlighter jqplot

I've many series of just two points on a graph to simulate a timeline. These points have a pointlabel. I'd like to have the name of that pointlabel in the highlighter. How do I do that?
please see my JsFiddle http://jsfiddle.net/NVbjv/8/
I'd tried to add a highlighter object to each series, and give it a format string. But how can I make this more dynamic?
I also like to only display time in the hoverbox-thingy in the bottom right. How do I get remove the ",1 " and ",2"?
The only idea that comes to my mind is to use a custom processing of the tooltip of highlighter and cursor. Something along the lines as it is presented here.
In your case you would apply the following code:
$("#container").bind('jqplotMouseMove', function(ev, gridpos, datapos, neighbor, plot) {
var date = new Date(datapos.xaxis);
var time = "" + (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":" + (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes());
$(".jqplot-cursor-tooltip").html(time + " Oi");
if (neighbor) {
$(".jqplot-highlighter-tooltip").html("Label name= " + neighbor.data[2] + "; time= " + time);
}
});
The working code sample is available here.
EDIT:
In Chrome I have noticed that the null is printed for the pointLabels therefore use empty strings for their values instead.

Making a value plural (Greater than, Less than) in Javascript

I have the following code:
$(function(){
var total_click = 0;
$("#mapKey a.showKey").click(function(){
total_click = total_click + 1;
$("#counter").text("I cheated " + total_click + " whole" + (total_click = 1 ? + ' time' + ((total_click > 1) ? 's ' : ' ') : ''));
return false;
});
});
I'm trying to have it output as such:
Clicked once: "I cheated 1 whole time."
Clicked more than once: "I cheated X whole times."
-- With an 's' at the end of "times".
The counter is working fine, it's just the last part making the "time" or "times" show up appropriately that I am having difficulty with.
Any ideas what I'm doing wrong?
Thanks!
Here is your problem: total_click = 1. Try changing it to total_click == 1. I don't see why you have that conditional in there however, as it won't work as you expect anyway. Try $("#counter").text("I cheated " + total_click + " whole time" + ((total_click == 1) ? ' ' : 's '));
You are not using the ternary operator correctly, and also assigning total_click to 1 instead of checking its value. I would suggest moving this to a function to simplify things.
function pluralize(singular, times) {
if (times == 1) return singular;
else return singular + 's';
}
Then change the string to
var text = "I cheated " + clicks + " whole " + pluralize("time", clicks);
Here's an example.
$(function(){
var total_click = 0;
$("#mapKey a.showKey").click(function(){
total_click = total_click + 1;
$("#counter").text("I cheated " + total_click + " whole " + (total_click == 1 ? "time" : "times");
return false;
});
});
It's okay to use suggested implementations for a trivial cases, however it will not scale for a bigger set of problems and will not work for multiple languages (or it will get ugly very fast).
With this in mind, I’ve created a very simple JavaScript library that can be used to pluralize words in almost any language. It transparently uses CLDR database for multiple locales. It’s API is very minimalistic and integration is extremely simple. It’s called Numerous.
I’ve also written a small introduction article to it: «How to pluralize any word in different languages using JavaScript?».
Feel free to use it in your project. I will also be glad for your feedback on it!

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

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 + '"'
// --^ --^
`

Categories

Resources