Asigning CSS property to variable in JavaScript [Polymer] - javascript

I have simple question about asigning values of CSS properties to some variables is JavaScript in Polymer app.
Assume I have one div with width:200px;. In some JavaScript function i want to change width to 200px+10px.
I know i can apply this in JS in this way div.style.top = '210px';, but this is not what I need!
I want to changing this width property, and have full control about this.
So I readed i can make some custom CSS variable to save my width:
:host {
--my-width: 200px;
}
div{
width: var(--my-width);
}
This is nice because now I have one CSS variable, and I can set this attribute to few selectors, elements.
The question is - how to get this variable in JS and change it in that way (pseudocode):
--my-width = --my-width + 10px
I know i can use this
this.updateStyles({
'--my-width': '210px'
});
to replace value, but I want to code something like this:
this.updateStyles({
'--my-width': '--my-width'.value + 10px
});
So that I could changing this width by adding some values (+10px) , not defining new (= 210px)
I'm asking about how to make this and about some good practices in polymer, how to do that.

You can use window.getComputedStyle and getPropertyValue:
const styles = window.getComputedStyle(this);
const myWidth = styles.getPropertyValue('--my-width');
const newWidth = `${parseFloat(myWidth) + 10}px`;
this.updateStyles({ '--my-width': newWidth });
It's worth reading the Polymer docs on custom properties. Although I'm not sure they're 100% up-to-date, they have some useful information re: Shady DOM.
An alternative, depending on your use case and the browsers you're targeting, is the CSS calc() function:
div {
width: calc(var(--my-width) + 10px);
}
You could do the same with updateStyles, of course.

Related

How to select an element based on a style value?

I am making a custom progress bar that I want to change color based on it's width value. i.e if it's width is less than 50% the bar is red, if it's greater then the bar is green.
I know I can use the attribute selector like so:
.p-bar[style*="width: 10"] {
background-color: red;
}
But doing it like this would mean I would have to asign a value every step of the way...
P.D. sass solutions acceptable, thanks.
Edit
P.P.D. js solution also acceptable... but I would like to know if there is defenetly no way to accomplish what I want with CSS.
Ok... so as it was said before it seems like it is not possible to to do what I was trying to do using only css.
However it seems pretty easy to change color based on value using javascript.
Here is the code I ended up using (I have a button to add 10% of "progress" AKA width to my bar ):
var progressed = 0; /* Variable to handle the width % */
$('.btnAddProgress').click(function(){
var progressBar = $(this).parent().find('.progress-bar'); /* Get the bar */
progressed += 10;
progressBar.css({
'width': progressed + '%', /* Apply the changed width */
});
var progPrcnt = progressBar.width() / progressBar.parent().width() * 100; /* Wanted to get the actual element width because I figured I would not always have a variable like my "progressed" which value matches the actual width */
if (progPrcnt < 50) {
progressBar.css({
'background-color': '#f00',
});
} else {
progressBar.css({
'background-color': '#0f0',
});
}
});
Anyways... It turns out it was fairly easy to do what I wanted to do using JS and ended up figuring it out quite soon, and then not wanting forgetting to come back to my post and point out how dumb I was.
Anyways as I always say I'ms still learning, thanks a lot for your help an patience.

How to force jQuery to change CSS value itself, instead of adding inline styles?

Developing my own grid system, I decided to use jQuery instead of adding classes for every width or height.
I found the code below from here to change the width of divs with jQuery, based on their classname:
$("[class*='tul-']").each(function(){
$(this).css("width", 100 / $(this).attr("class").substring(4,5) + "%");
});
So, something like: <div class="tul-5"></div> should have a 100 / 5 + "%" = 20% width.
The problem is that jQuery adds inline-css instead of changing the value of width property in class (tul-5) itself. The <div class="tul-5"></div> becomes <div class="tul-5" style="width: 20%"></div>.
What I want is:
tul-5 {
width: 20%; /*change this*/
}
I want to get rid of inline-css because of SEO and the mess it makes.
Things I tried:
I tried creating classes with a default width size, but no luck:
.tul-1, .tul-2, .tul-3 {
width: 50px;
}
I've also tried pure Js code from the page mentioned above, but it also adds inline-css.
P.S.: I haven't declared any classes starting with tul.

Modify CSS classes using Javascript

I was wondering if there is an easy way to change the CSS classes in JavaScript.
I have gone through all other similar questions here and I couldn't find an straight-forward and simple solution.
what I'm trying to do is to set the width and height of a <div> to match an image that I have on my site (upon loading). I already know the picture dimensions and I can set my CSS to that - but I want my script to figure this out on its own.
After hours of r&d (I'm a beginner), this is what I came up with:
var myImg = new Image();
myImg.src = "img/default.jpg";
myImg.onload = function(){
var imgWidth = this.width;
var imgHeight = this.height;
document.getElementById("myBg").setAttribute('style', "height :"+ imgHeight + "px");
document.getElementById("myBg").setAttribute('style', "width :"+ imgWidth + "px");
};
However, this only sets the width of the element with id "myBg". If I reverse the order of the height and width, then it only sets the height to the image's height.
It seems like first it sets the height of the element to the image height but right after it moves to the next statement to set the width, the height value goes back to what it what defined originally in css.
I did further research online and seems like changing the css (inserting new attributes, removing, etc.) using JavaScript is not an easy task. It is done through
document.styleSheets[i].cssRules[i] or document.styleSheets[i].addRule
type of commands, but all the tutorials online and here on stackoverflow were confusing and complicated.
I was wondering if anyone familiar with document.styleSheets can explain this to me simply?
Imagine I have this class in my separate css file:
.container
{
height: 600px;
width: 500px;
}
I want the height and width to change to the dimension of the picture upon loading. How do I do this?
I don't want to define a new "style" element in my html file, I want to change the css file.
I'm not supposed to know the image dimension before it loads to the page.
no jquery please, I want to do this using only standard JavaScript.
Thank you.
The reason only one or the other works is because in your second line of code, you destroy the whole style attribute, and recreate it. Note that setAttribute() overwrites the whole attribute.
A better solution would be to use the element.style property, not the attribute;
var bg = document.getElementById("myBg");
bg.style.width = imgWidth + "px";
bg.style.height = imgHeight + "px";
You can grab all elements with class container and apply it to each of them like this:
var elements = document.querySelectorAll('.container');
for(var i=0; i<elements.length; i++){
elements[i].style.width = imgWidth + "px";
elements[i].style.height = imgHeight + "px";
}
Note querySelectorAll isn't supported by IE7 or lower, if you need those then there are shims for getElementsByClassName() here on SO.
If your rules start incrementing you could extract your css to a new class and switch classes:
CSS:
.container-1{
/* A set of rules */
}
.container-2{
/* A set of rules */
}
JavaScript:
element.className = element.className.replace(/container-1/, 'container-2')
var object = document.createElement('container');
object.style.width= "500px";
object.style.height= "600px";
You can also add values to this if you hold the dimensions in variables
var height = 600;
var width = 500;
You can increment when needed
height += 5;
Here is something you might find useful. It may offer you some insight on how you can solve a problem with many different approaches, seeing as though you are new to js.

How can I check if CSS calc() is available using JavaScript?

Is there a way to check if the CSS function calc is available using JavaScript?
I found lot of questions and articles about getting the same behaviour as calc using jQuery, but how can I only check if it's available?
In Modernizr you can find the test as css-calc currently in the non-core detects. They use the following code:
Modernizr.addTest('csscalc', function() {
var prop = 'width:';
var value = 'calc(10px);';
var el = document.createElement('div');
el.style.cssText = prop + Modernizr._prefixes.join(value + prop);
return !!el.style.length;
});
A bit late to the party but I figured I should share this because I was myself struggling with it. Came up with the idea of by using jQuery, I can create a div that uses the calc() value in a CSS property (such as width in this case) and also a fallback width in case the browser does not support calc(). Now to check whether it supports it or not, this is what I did:
Let's create the CSS style for the currently "non-existing" div element.
/* CSS3 calc() fallback */
#css3-calc {
width: 10px;
width: calc(10px + 10px);
display: none;
}
Now, if the browser does not support calc(), the element would return a width value of 10. If it does support it, it would return with 20. Doesn't matter what the values are exactly, but as long as the two width properties have different values in the end (in this case 10 and 20).
Now for the actual script. It's pretty simple and I suppose it's possible with regular JavaScript too, but here's the jQuery script:
// CSS3 calc() fallback (for unsupported browsers)
$('body').append('<div id="css3-calc"></div>');
if( $('#css3-calc').width() == 10) {
// Put fallback code here!
}
$('#css3-calc').remove(); // Remove the test element
Alternatively, native javascript check, and width:
#css3-calc { width: 1px; width: calc(1px + 1px); }
if( document.getElementById('css3-calc').clientWidth==1 ){
// clientHeight if you need height
/* ... */
}
Calc detection was added to modernizer according to their news page.
http://modernizr.com/news/
As well as tightening up support for existing tests, we've also added
a number of new detects, many submitted by the community:
[...]
css-calc
var cssCheck = document.createElement("DIV");
cssCheck.style.marginLeft = "calc(1px)";
if (cssCheck.style.getPropertyValue("margin-left"))
{
alert("calc is supported");
}
cssCheck = null;

Find the "potential" width of a hidden element

I'm currently extending the lavalamp plugin to work on dropdown menus but I've encountered a small problem. I need to know the offsetWidth of an element that is hidden. Now clearly this question makes no sense, rather what I'm looking for is the offsetWidth of the element were it not hidden.
Is the solution to show it, grab the width, then hide again? There must be a better way...
The width of an element that has CSS visibility: hidden is measurable. It's only when it's display: none that it's not rendered at all. So if it's certain the elements are going to be absolutely-positioned (so they don't cause a layout change when displayed), simply use css('visibility', 'hidden') to hide your element instead of hide() and you should be OK measuring the width.
Otherwise, yes, show-measure-hide does work.
The only thing I can think of is to show it (or a clone of it) to allow retrieval of the offsetWidth.
For this measurement step, just make its position absolute and its x or y value a big negative, so it will render but not be visible to the user.
You can use the following function to get the outer width of an element that is inside a hidden container.
$.fn.getHiddenOffsetWidth = function () {
// save a reference to a cloned element that can be measured
var $hiddenElement = $(this).clone().appendTo('body');
// calculate the width of the clone
var width = $hiddenElement.outerWidth();
// remove the clone from the DOM
$hiddenElement.remove();
return width;
};
You can change .outerWidth() to .offsetWidth() for your situation.
The function first clones the element, copying it to a place where it will be visible. It then retrieves the offset width and finally removes the clone. The following snippet illustrates a situation where this function would be perfect:
<style>
.container-inner {
display: none;
}
.measure-me {
width: 120px;
}
</style>
<div class="container-outer">
<div class="container-inner">
<div class="measure-me"></div>
</div>
</div>
Please be aware that if there is CSS applied to the element that changes the width of the element that won't be applied if it's a direct descendant of body, then this method won't work. So something like this will mean that the function doesn't work:
.container-outer .measure-me {
width: 100px;
}
You'll either need to:
change the specificity of the CSS selector ie. .measure-me { width: 100px; }
change the appendTo() to add the clone to a place where your CSS will also be applied to the clone. Ensure that where ever you do put it, that the element will be visible: .appendTo('.container-outer')
Again, this function assumes that the element is only hidden because it's inside a hidden container. If the element itself is display:none, you can simply add some code to make the clone visible before you retrieve it's offset width. Something like this:
$.fn.getHiddenOffsetWidth = function () {
var hiddenElement $(this)
width = 0;
// make the element measurable
hiddenElement.show();
// calculate the width of the element
width = hiddenElement.outerWidth();
// hide the element again
hiddenElement.hide();
return width;
}
This would work in a situation like this:
<style>
.measure-me {
display: none;
width: 120px;
}
</style>
<div class="container">
<div class="measure-me"></div>
</div>
Two options:
position the element outside the viewport (ex: left:-10000px)
use visibility: hidden or opacity: 0 instead of hide().
Either way will work as hiding the element but still being able to get the computed width. Be careful with Safari on thi, it's awfully fast and sometimes too fast...
Actual jQuery plugin!
Usage:
console.log('width without actual: ' + $('#hidden').width());
console.log('width with actual: ' + $('#hidden').actual('width'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.actual/1.0.19/jquery.actual.min.js"></script>
<div style="width: 100px; display: none;">
<div id="hidden"></div>
</div>
If you know the element to be the full width of a parent element another approach is to create a recursive method:
es5:
var getWidth;
getWidth = function($el){
return $el.offsetWidth || getWidth($el.parentElement);
}
var width = getWidth(document.getElementById('the-element'));
es6:
let getWidth
getWidth = ($el) => $el.offsetWidth || getWidth($el.parentElement)
const width = getWidth(document.getElementById('the-element'))
What I did was ;
by the time hiding that element, stored its width in its dataset.
It only will work for you if you can hide programmatically.
ie.
When Hiding ;
var elem = $("selectorOfElement");
elem.dataset.orgWidth = elem.clientWidth;
Later when getting ;
var elem = $("selectorOfElement");
var originalWidthWas = elem.dataset.orgWidth;
thats because its hidden via display: none; What ive done in the past is to make a "reciever" div which i use absolute positioning on to get it off the page. Then i load the new element into that, grab the dimensions and then remove it when im done - then remove the reciever when im done.
Another thing you can do is to not use hide(); but to instead set visibility: hidden; display: ; However this means the blank area will be rendered wherever the node is attached.
var $hiddenElement = $('#id_of_your_item').clone().css({ left: -10000, top: -10000, position: 'absolute', display: 'inline', visibility: 'visible' }).appendTo('body');
var width = parseInt($hiddenElement.outerWidth());
$hiddenElement.remove();
I try to find working function for hidden element but I realize that CSS is much complex than everyone think. There are a lot of new layout techniques in CSS3 that might not work for all previous answers like flexible box, grid, column or even element inside complex parent element.
flexibox example
I think the only sustainable & simple solution is real-time rendering. At that time, browser should give you that correct element size.
Sadly, JavaScript does not provide any direct event to notify when element is showed or hidden. However, I create some function based on DOM Attribute Modified API that will execute callback function when visibility of element is changed.
$('[selector]').onVisibleChanged(function(e, isVisible)
{
var realWidth = $('[selector]').width();
var realHeight = $('[selector]').height();
// render or adjust something
});
For more information, Please visit at my project GitHub.
https://github.com/Soul-Master/visible.event.js
demo: http://jsbin.com/ETiGIre/7
Sorry I am late to this conversation. I am surprised no one has mentioned getComputedStyle. (Note this only works if the CSS sets a width value)
Grab the element:
let yourEle = document.getElementById('this-ele-id');
and use the function:
getComputedStyle(yourEle).width
This returns a string so you will have to remove the numbers from the string.
This works even when the element's display style is set to none.
Other articles to read about this includes here at zellwk.com

Categories

Resources