Globally rounding math in jQuery/javascript - javascript

Just wondering if there was a way of adding in a custom jQuery method or similar to ensure all calculations are rounded to the nearest integer? E.g. for working out widths etc.
Thanks!

No, it would be impossible.
The closest you can do is change how calculations are performed in jQuery methods.
You can't change how the language itself performs arithmetic operations.
Operators can't be overriden in the JavaScript language.
Here is how you would over-ride jQuery's .width for example (this is not recommended for production code!)
$.fn.oldwidth = $.fn.width;
$.fn.width = function (elem) {
if(elem == null){ // no param, getter
return $.fn.oldwidth.call(this);
}
if (typeof elem === "string") { // 12px for example
var numPart = parseInt(elem); //get just the 12
var unitPart = elem.match(/[a-zA-Z]/g).join(""); //get the number part
return $.fn.oldwidth.call(this,Math.floor(numPart) + unitPart);
}
return $.fn.oldwidth.call(this,Math.floor(elem));
}
Working Demo
This would do:
$("#some").width("5.6em");
alert($("#some").width()); // Alerts 80 with the above code, 90 without.

if you put all calculations in a specific class you could round them globally
var Arithmetics = //class of all calc's
for(each element in arithmetics){
element = Math.round(element)
}

I don't know what kind of calculation you're trying to do, but if it's simple repetitive operations you can do a function that handle an operation and return the rounded result...
Like
function calculateSomething(operation){
// ???
return floor(result);
}

Related

Check if elements are part of wrapper [duplicate]

How can I check if one DOM element is a child of another DOM element? Are there any built in methods for this? For example, something like:
if (element1.hasDescendant(element2))
or
if (element2.hasParent(element1))
If not then any ideas how to do this? It also needs to be cross browser. I should also mention that the child could be nested many levels below the parent.
You should use Node.contains, since it's now standard and available in all browsers.
https://developer.mozilla.org/en-US/docs/Web/API/Node.contains
Update: There's now a native way to achieve this. Node.contains(). Mentioned in comment and below answers as well.
Old answer:
Using the parentNode property should work. It's also pretty safe from a cross-browser standpoint. If the relationship is known to be one level deep, you could check it simply:
if (element2.parentNode == element1) { ... }
If the the child can be nested arbitrarily deep inside the parent, you could use a function similar to the following to test for the relationship:
function isDescendant(parent, child) {
var node = child.parentNode;
while (node != null) {
if (node == parent) {
return true;
}
node = node.parentNode;
}
return false;
}
I just had to share 'mine'.
Although conceptually the same as Asaph's answer (benefiting from the same cross-browser compatibility, even IE6), it is a lot smaller and comes in handy when size is at a premium and/or when it is not needed so often.
function childOf(/*child node*/c, /*parent node*/p){ //returns boolean
while((c=c.parentNode)&&c!==p);
return !!c;
}
..or as one-liner (just 64 chars!):
function childOf(c,p){while((c=c.parentNode)&&c!==p);return !!c}
and jsfiddle here.
Usage:
childOf(child, parent) returns boolean true|false.
Explanation:
while evaluates as long as the while-condition evaluates to true.
The && (AND) operator returns this boolean true/false after evaluating the left-hand side and the right-hand side, but only if the left-hand side was true (left-hand && right-hand).
The left-hand side (of &&) is: (c=c.parentNode).
This will first assign the parentNode of c to c and then the AND operator will evaluate the resulting c as a boolean.
Since parentNode returns null if there is no parent left and null is converted to false, the while-loop will correctly stop when there are no more parents.
The right-hand side (of &&) is: c!==p.
The !== comparison operator is 'not exactly equal to'. So if the child's parent isn't the parent (you specified) it evaluates to true, but if the child's parent is the parent then it evaluates to false.
So if c!==p evaluates to false, then the && operator returns false as the while-condition and the while-loop stops. (Note there is no need for a while-body and the closing ; semicolon is required.)
So when the while-loop ends, c is either a node (not null) when it found a parent OR it is null (when the loop ran through to the end without finding a match).
Thus we simply return that fact (converted as boolean value, instead of the node) with: return !!c;: the ! (NOT operator) inverts a boolean value (true becomes false and vice-versa).
!c converts c (node or null) to a boolean before it can invert that value. So adding a second ! (!!c) converts this false back to true (which is why a double !! is often used to 'convert anything to boolean').
Extra:
The function's body/payload is so small that, depending on case (like when it is not used often and appears just once in the code), one could even omit the function (wrapping) and just use the while-loop:
var a=document.getElementById('child'),
b=document.getElementById('parent'),
c;
c=a; while((c=c.parentNode)&&c!==b); //c=!!c;
if(!!c){ //`if(c)` if `c=!!c;` was used after while-loop above
//do stuff
}
instead of:
var a=document.getElementById('child'),
b=document.getElementById('parent'),
c;
function childOf(c,p){while((c=c.parentNode)&&c!==p);return !!c}
c=childOf(a, b);
if(c){
//do stuff
}
Another solution that wasn't mentioned:
Example Here
var parent = document.querySelector('.parent');
if (parent.querySelector('.child') !== null) {
// .. it's a child
}
It doesn't matter whether the element is a direct child, it will work at any depth.
Alternatively, using the .contains() method:
Example Here
var parent = document.querySelector('.parent'),
child = document.querySelector('.child');
if (parent.contains(child)) {
// .. it's a child
}
You can use the contains method
var result = parent.contains(child);
or you can try to use compareDocumentPosition()
var result = nodeA.compareDocumentPosition(nodeB);
The last one is more powerful: it return a bitmask as result.
Take a look at Node#compareDocumentPosition.
function isDescendant(ancestor,descendant){
return ancestor.compareDocumentPosition(descendant) &
Node.DOCUMENT_POSITION_CONTAINS;
}
function isAncestor(descendant,ancestor){
return descendant.compareDocumentPosition(ancestor) &
Node.DOCUMENT_POSITION_CONTAINED_BY;
}
Other relationships include DOCUMENT_POSITION_DISCONNECTED, DOCUMENT_POSITION_PRECEDING, and DOCUMENT_POSITION_FOLLOWING.
Not supported in IE<=8.
I came across a wonderful piece of code to check whether or not an element is a child of another element. I have to use this because IE doesn't support the .contains element method. Hope this will help others as well.
Below is the function:
function isChildOf(childObject, containerObject) {
var returnValue = false;
var currentObject;
if (typeof containerObject === 'string') {
containerObject = document.getElementById(containerObject);
}
if (typeof childObject === 'string') {
childObject = document.getElementById(childObject);
}
currentObject = childObject.parentNode;
while (currentObject !== undefined) {
if (currentObject === document.body) {
break;
}
if (currentObject.id == containerObject.id) {
returnValue = true;
break;
}
// Move up the hierarchy
currentObject = currentObject.parentNode;
}
return returnValue;
}
Consider using closest('.selector')
It returns null if neither element nor any of its ancestors matches the selector. Alternatively returns the element which was found
try this one:
x = document.getElementById("td35");
if (x.childElementCount > 0) {
x = document.getElementById("LastRow");
x.style.display = "block";
}
else {
x = document.getElementById("LastRow");
x.style.display = "none";
}
TL;DR: a library
I advise using something like dom-helpers, written by the react team as a regular JS lib.
In their contains implementation you will see a Node#contains based implementation with a Node#compareDocumentPosition fallback.
Support for very old browsers e.g. IE <9 would not be given, which I find acceptable.
This answer incorporates the above ones, however I would advise against looping yourself.

Unable to set number in .data() method

I am trying to set a number as my data type dynamically using .data() method in jQuery, but so far no luck. This works using the .attr() method as I have listed in below. Why does the .data() method not work with numbers?
var container = $(this).find('#container'); // element which should have the data
Attempt 1:
container.data(24, "opacity:0;");
Attempt 2:
container.data("24", "opacity:0;");
The following code works using .attr():
container.attr("data-123", 1223);
My personal code:
function loader($div, $page) {
$div.load(siteURL + $page + '/ #container', function() {
var container = $(this).find('#container');
container.data("24", "opacity:0;");
container.attr("data-24", "opacity:0;"); //this works...
});
}
loader($('section#about'), 'about');
UPDATE: Here is a jsFiddle
Historically jQuery supported the data() method by keeping track of values set using it in a separate data structure. This allowed you do store things like objects using the API.
While retrieving data, the API will check both the data attribute as well as well as its internal store for the value.
Setting, however still goes straight to the internal store.
Since the question has changed significantly:
$.data will fail when sending a number.
Doing this in the console you will see the following (none of these affect the markup of the element itself):
// Error
$('div').data(24, 'foo')
TypeError: Object 24 has no method 'replace'
// Success
$('div').data("24", 'foo')
b.fn.b.init[966]
$('div').data("24")
"foo"
// Success
$('div').data("24", 24)
b.fn.b.init[966]
$('div').data("24")
24
None of these will affect a data attribute on the element itself. The end result of the markup will be:
<div>Hello</div>
If you are looking to set a data-xxx attribute on the element, or any attribute for that matter, an elements attribute must begin with an alpha character:
// Error
$('div').attr("24", "opacity:0")
InvalidCharacterError: An invalid or illegal character was specified, such as in an XML name.
// Success
$('div').attr("data-24", "opacity:0")
b.fn.b.init[966]
The end result of the successful call will be:
<div data-24="opacity:0">Hello</div>
skrollr does not use jQuery's .data function it parses the DOM elements attribute list which is why using .attr("data-24" works as the attribute is added to the DOM attribute list
.data("24","somevalue") does not update the DOM elements attribute list,
.attr("data-24","somevalue") however does update the DOM elemetns attribute list which allows skrollr to parse the new style.
FROM SKROLLR.JS
Starting at Line 343:
//Iterate over all attributes and search for key frame attributes.
var attributeIndex = 0;
var attributesLength = el.attributes.length;
for (; attributeIndex < attributesLength; attributeIndex++) {
var attr = el.attributes[attributeIndex];
if(attr.name === 'data-anchor-target') {
anchorTarget = document.querySelector(attr.value);
if(anchorTarget === null) {
throw 'Unable to find anchor target "' + attr.value + '"';
}
continue;
}
//Global smooth scrolling can be overridden by the element attribute.
if(attr.name === 'data-smooth-scrolling') {
smoothScrollThis = attr.value !== 'off';
continue;
}
//Global edge strategy can be overridden by the element attribute.
if(attr.name === 'data-edge-strategy') {
edgeStrategy = attr.value;
continue;
}
var match = attr.name.match(rxKeyframeAttribute);
if(match === null) {
continue;
}
var constant = match[1];
//If there is a constant, get it's value or fall back to 0.
constant = constant && _constants[constant.substr(1)] || 0;
//Parse key frame offset. If undefined will be casted to 0.
var offset = (match[2] | 0) + constant;
var anchor1 = match[3];
//If second anchor is not set, the first will be taken for both.
var anchor2 = match[4] || anchor1;
var kf = {
offset: offset,
props: attr.value,
//Point back to the element as well.
element: el
};
keyFrames.push(kf);
//"absolute" (or "classic") mode, where numbers mean absolute scroll offset.
if(!anchor1 || anchor1 === ANCHOR_START || anchor1 === ANCHOR_END) {
kf.mode = 'absolute';
//data-end needs to be calculated after all key frames are know.
if(anchor1 === ANCHOR_END) {
kf.isEnd = true;
} else {
//For data-start we can already set the key frame w/o calculations.
//#59: "scale" options should only affect absolute mode.
kf.frame = offset * _scale;
delete kf.offset;
}
}
//"relative" mode, where numbers are relative to anchors.
else {
kf.mode = 'relative';
kf.anchors = [anchor1, anchor2];
}
}
container.data("24", "opacity:0;"); works right? First parameter must be a String (as per jQuery spec).
Because the data() method expects a string.
Hence I guess it'll be breaking if you pass it a number!
Can you try using the jQuery object itself:
var container = $(this).find('#container');
jQuery.data(container, "24", "opacity:0;");
alert("24 is equal to: " + jQuery.data(container, "24") );
You should note this will not affect the DOM as it uses jQuery's local storage.
JSFiddle: http://jsfiddle.net/markwylde/8Q5Yh/1/
container.data("24") actually works for me.
It depends on the version of jQuery too. When you call .data as a setter, all versions will call either .split or .replace which are String methods, not Number methods. Using .data(24) as an accessor seems to work past version 1.8.
This may also be browser dependent as dataset is not available in some browsers.
My advice would be to use a descriptive name for the data rather than just a number (unless you're talking about form 24 or something, but then why not use form24?)
EDIT: Using .data does not alter the HTML if the dataset attribute is available on the element. Using .attr always sets an attribute which will alter the HTML. This has nothing to do with using strings vs. numbers.

How to find a jQuery selector (using :contains) result set's complement

What is the best way to get the complement of a jQuery selector's result set? I want to do something like the following:
jQuery(this).find("div:contains('someValue')").show();
But I want the complement of this selection hidden:
jQuery(this).find("div:not(:contains('someValue'))").hide();
Is there a more elegant solution to this than just executing the complementary selector? An alternative I can see is finding all divs first, storing the result, and filter this:
var results = jQuery(this).find("div");
results.find(":contains('someValue')").show();
results.find(":not(:contains('someValue'))").hide();
But that doesn't seem that much better. Any ideas?
var results = jQuery(this).find("div"),
selector = ":contains('someValue')";
results.filter(selector).show();
results.not(selector).hide();
as #Simon mentioned in the comments there is a way to improve this particular solution:
var results = jQuery("div", this),
selector = ":contains('someValue')";
results.filter(selector).show();
results.not(selector).hide();
Try like this,
jQuery(this).find("div").hide();
jQuery(this).find("div:contains('someValue')").show();
Well, I think your code is fairly good, but another option could be running this single statement:
jQuery(this).find("div").each(
function() {
var me = $(this);
var f = me.is(":contains('someValue')") ? "show" : "hide";
me[f]();
}
);
/** $.grepl
* uses a regular expression for text matching within an internal $.grep.
*/
$.extend({
"grepl": function(el, exp){
exp=new RegExp(exp,'gi'); // create RegExp
return $(
this.grep( el, function(n,i){ // run internal grep
return el[i].textContent.match(exp) != null; // match RegExp against textContent
})
);
}
});
$.grepl( $('div'), '^.*someRegexp.*$' ).css('display','none'); // usage of the function
I know that this does not exactly use the ":contains" expression, but the result should be the same.

adding chr to the number Prototype

I have the following function:
var chr = function(X) {
return String.fromCharCode(X)
}
But I would like to use i.chr() instead of chr(i).
Q: How do I add chr() to the number prototype?
Number.prototype.chr = function() {
return String.fromCharCode(this);
}
var n = 33;
console.log(n.chr());
http://jsfiddle.net/CXWeV/
Also, as Bryan points out, the following will work:
console.log((33).chr());
console.log(Number(33).chr());
But, the following does not work:
33.chr();
EDIT: Although, as Gumbo points out, this does:
33..chr();
As well as a check if the property already exists (see Erik's answer for another way to check):
if (!Number.prototype.chr) {
Number.prototype.chr = function() {
return String.fromCharCode(this);
}
}
if (!Number.prototype.hasOwnProperty('chr')) {
Number.prototype.chr = function() {
return String.fromCharCode(this);
};
}
To use this the number must be in a variable or wrapped in parentheses. Be aware that converting a scalar number to a Number object (called boxing) has an overhead. If you are doing the conversion repeatedly on the same value, you'll want to explicitly convert it to an object first with Number().
Note that simply doing String.fromCharCode might be easier or more clear in some situations.
The normal way, really. Note the importance of surrounding the number in parentheses (or storing it in a variable), as a dot would normally indicate a decimal point:
Number.prototype.chr = function () {
return String.fromCharCode(this);
}
alert((97).chr()); // alerts "a"
I'm not sure whether this works in all browsers, but I'm assuming it does.
Interactive Example

Why does this function work for literals but not for more complex expressions?

I am having some insidious JavaScript problem that I need help with. I am generating HTML from a JSON structure. The idea is that I should be able to pass a list like:
['b',{'class':'${class_name}'}, ['i', {}, 'Some text goes here']]
...and get (if class_name = 'foo')...
<b class='foo'><i>Some text goes here.</i></b>
I use the following functions:
function replaceVariableSequences(str, vars) {
/* #TODO Compiling two regexes is probably suboptimal. */
var patIdent = /(\$\{\w+\})/; // For identification.
var patExtr = /\$\{(\w+)\}/; // For extraction.
var pieces = str.split(patIdent);
for(var i = 0; i < pieces.length; i++) {
if (matches = pieces[i].match(patExtr)) {
pieces[i] = vars[matches[1]];
}
}
return pieces.join('');
}
function renderLogicalElement(vars, doc) {
if (typeof(doc[0]) == 'string') {
/* Arg represents an element. */
/* First, perform variable substitution on the attribute values. */
if (doc[1] != {}) {
for(var i in doc[1]) {
doc[1][i] = replaceVariableSequences(doc[1][i], vars);
}
}
/* Create element and store in a placeholder variable so you can
append text or nodes later. */
var elementToReturn = createDOM(doc[0], doc[1]);
} else if (isArrayLike(doc[0])) {
/* Arg is a list of elements. */
return map(partial(renderLogicalElement, vars), doc);
}
if (typeof(doc[2]) == 'string') {
/* Arg is literal text used as innerHTML. */
elementToReturn.innerHTML = doc[2];
} else if (isArrayLike(doc[2])) {
/* Arg either (a) represents an element
or (b) represents a list of elements. */
appendChildNodes(elementToReturn, renderLogicalElement(vars, doc[2]));
}
return elementToReturn;
}
This works beautifully sometimes, but not others. Example from the calling code:
/* Correct; Works as expected. */
var siblings = findChildElements($('kv_body'), ['tr']);
var new_id = 4;
appendChildNodes($('kv_body'),
renderLogicalElement({'id': new_id},
templates['kveKeyValue']));
/* Incorrect; Substitutes "0" for the expression instead of the value of
`siblings.length` . */
var siblings = findChildElements($('kv_body'), ['tr']);
var new_id = siblings.length; // Notice change here!
appendChildNodes($('kv_body'),
renderLogicalElement({'id': new_id},
templates['kveKeyValue']));
When I trap out the first argument of renderLogicalElement() using alert(), I see a zero. Why is this?? I feel like it's some JavaScript type thing, possibly having to do with object literals, that I'm not aware of.
Edit: I have this code hooked up to the click event for a button on my page. Each click adds a new row to the <tbody> element whose ID is kv_body. The first time this function is called, siblings is indeed zero. However, once we add a <tr> to the mix, siblings.length evaluates to the proper count, increasing each time we add a <tr>. Sorry for not being clearer!! :)
Thanks in advance for any advice you can give.
If new_id is 0, doesn't it mean that siblings.length is 0? Maybe there is really no sibling.
Perhaps siblings.length is actually 0? Try debugging further (e.g. with Firebug)
OK, I fixed it. As it turns out, I was modifying my source JSON object with the first function call (because in JS you are basically just passing pointers around). I needed to write a copy function that would make a new copy of the relevant data.
http://my.opera.com/GreyWyvern/blog/show.dml/1725165
I ended up removing this as a prototype function and just making a regular old function.

Categories

Resources