I want to get the height of an element and pass it into a css variable. The issue im having is when i try to pass that number into the navHeight variable it ends up returning as undefined.
<script>
let navHeightTest = document.getElementById("navbar").offsetHeight;
console.log(navHeightTest); // Returns the nav height as a number
let navHeight = Document.documentElement.style.setProperty('--nav-height', navHeightTest);
console.log(`Nav Height=${navHeight}`); // Returns undefined
</script>
CSS
:root {
--nav-height: 101px; /* Default Fallback Value */
}
.dynamic-margin {
margin-top: calc(var(--nav-height) + 2.5rem) !important;
}
Good question - this can get confusing because setProperty returns undefined, not the value you just set.
Check out the Return value entry in the docs: https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/setProperty#return_value
If you observe that the --nav-height variable isn't being updated either it might be because you're missing the units when you call setProperty. Since your default in the CSS is in pixels, and offsetHeight reports the number in pixels, I'm guessing you want pixels. Note the 'px' at the very end of the line.
let navHeight = Document.documentElement.style.setProperty('--nav-height', navHeightTest + 'px');
Related
I have two variables: width and height. Assume that the variables are two random positive numbers.
Width and height must always equal the ratio of 1.4:1.
To put it another way,
width / height === 1.4
Must always evaluate to true.
In JavaScript, how do I change width and height so that they always equal this constant ratio?
const obj = {
width: 100 * Math.random(),
get height() { return this.width / 1.4; },
set height(v) { this.width = v * 1.4; },
};
Use getters and setters to change them both at the same time.
If you're getting two random numbers and need to change them to equal the ratio, you'll need to pick one and define the other based on it. For instance:
width = height * 1.4;
I am trying to transform the html element programmatically. Updated transform value changed in console-tab but not changed in element-tab in the browser.
onDragStart(element: HTMLElement) {
this.elementRef = element;
var style = window.getComputedStyle(element);
var matrix = new WebKitCSSMatrix(style.webkitTransform);
this.translateY = matrix.m42;
console.log(this.translateY) //outputs: 85, because its current Y-location is 85px
element.style.transform = "translate( 0px," + this.translateY + "px)";
console.log(element);
}
where I am wrong? I am facing this issue about last 24 hours.
syntactically and logically the question was correct.
Actually I have not set the top-attribute of the html-element that's why it was behaving non-ideally (going at location translation(0px,0px) from its current location) on first click.
First set top, then transform it anywhere because setting top sustains its first position and then you may translate it somewhere
I have this function that returns a random color, but I want to apply it to jQuery .animate() function.
How can I do that?
var colors = ["rgb(120,25,25)", "rgb(50,100,130)", "rgb(30,95,45)", "rgb(55,30,90)"];
function randomBackground() {
return colors[Math.floor(Math.random() * messages.length)];
}
$("#menu").animate({background: randomBackground()});
You could do:
var colors = ["rgb(120,25,25)", "rgb(50,100,130)", "rgb(30,95,45)", "rgb(55,30,90)"];
function randomBackground() {
return colors[Math.floor(Math.random() * colors.length)];
//use colors.length, not messages.length
}
var bgcolor = randomBackground();
$("#menu").animate({background: bgcolor });
sorry for you but if you read the jQuery documentation :
All animated properties should be animated to a single numeric value, except as noted below; most properties that are non-numeric cannot be animated using basic jQuery functionality. (For example, width, height, or left can be animated but background-color cannot be.) Property values are treated as a number of pixels unless otherwise specified. The units em and % can be specified where applicable.
that meens you cannot do the background color change using animate()
Consider the following top forum contributors podium: Live demo
As you can see, the heights of the stands are constant. I would like to set the height according to the contribution percentage, so that if the first and the second places are 25.6% and 25.8% accordingly, the corresponding stands heights will be almost the same.
How would you calculate the heights based on contribution percentages ?
You need to pass the height percent with the "%" in the value passed to the height function.
Change the calc_heights functions to as given below.
Try this:
$(function() {
var first = 42.3;
var second = 34.2;
var third = 10.7;
var heights = calc_heights(first, second, third);
$(".first").height(heights[0] + "%").html(first);
$(".second").height(heights[1] + "%").html(second);
$(".third").height(heights[2] + "%").html(third);
});
function calc_heights(first, second, third) {
var total = (first+second+third)/100;
return [first/total, second/total, third/total];
}
Working example # http://jsfiddle.net/khTrx/1/
I know that it is bad practice to write code like this:
var createBox = function(width, height, margin){
alert("Margin is set to " + margin);
//margin is undefined in this context or why?
var margin = margin || 2;
alert("Margin is now " + margin);
}
createBox(0,0,0);
But can someone please explain, why margin is always set to 2?
Is it because it is undefined in the direct context of initializing a variable with the same name inside the function?
edit: sorry, I got the problem wrong ...
Please give a small hint :)
Regards, Tom
The || operator in JavaScript returns the value of the first operand if the first operand is truthy. Otherwise it returns the value of the second operand. It doesn't return 1/0, or true/false, as in some other languages.
Therefore when the margin argument holds a falsy value, such as 0 or undefined, it will return 2, since these are both falsy values in JavaScript.
The falsy values in JavaScript are: an empty string "", the null value, a value of 0, the NaN value, the boolean value false, and also undefined.
What you describe is a very common idiom in JavaScript. In fact the || operator is sometimes called the default operator1. You can use it to assign default values to variables when they are undefined. The problem in this case is that since 0 is a valid argument, the default operator is not behaving as required. You may want to do the following instead:
margin = typeof margin === 'undefined' ? 2 : margin;
1 Douglas Crockford: The Elements of JavaScript Style - Part 2 - Idioms.
If you call createBox(0,0,0), then margin is 0 (which has the truth value of false), so the expression margin || 2 becomes 0 || 2 which is equal to 2.
0 evaluates to false List of Truthy Values
// This function creates a new box by receiving three parameters
var createBox = function(width, height, margin){
// Output the margin of the box, zero in current case
alert("Margin is set to " + margin);
// If the margin is zero or undefined, '' set default value to 2
var margin = margin || 2;
// Output the new value of the margin which is 2
alert("Margin is now " + margin);
}
// here will show Margin: 0 after that Margin: 2
createBox(0,0,0);
// here will show Margin: 1 after that Margin: 1
createBox(0,0,1);
// here will show Margin: 3 after that Margin: 3
createBox(1,2,3);