Change class attribute dynamically inline with tailwind - javascript

How do I pass in a dynamic value using a string literal with tailwind inline css?
For example I want to change the width dynamically, and not use tailwinds premade w-1, w-2, etc...
<div
class="p-1 border-2 width: {createTimeBlock(
show.startTime,
show.endTime,
)}px">
{show.startTime} to {show.endTime}
</div>

The correct syntax would be w-[{...}px], but Tailwind relies to classes to be statically known, so this will probably not work.
The easiest thing would probably be to just use style:width="..." or style="width: ...". Though this will have high precedence due to being an inline style.
Alternatively, you can create a local component class that reads width from a custom property, then set the property using CSS attribute syntax, e.g. --width="..." (for components) or via style as style="--width: ...".

The other way around, if createTimeBlock will return a fixed set of values ( say [v1, v2, .... vN] ) for which there is a fixed set of width values to set ( assuming creatTimeBlock returns only increments of 15mins for example ), you can do this.
<script>
$timeblock = createTimeBlock( startTime, endTime );
</script>
<div
class="p-1 border-2..."
class:width_v1={timeblock === v1}
class:width_v2={timeblock === v2}
...
class:width_vN={timeblock === vN}
>
{startTime} to {endTime}
</div>
<style>
.width_v1{
width: v1_width_px;
}
.width_v2{ width: v2_width_px; }
....
.width_vN{ width: vN_width_px; }
</style>
Note, the actual .width_v1 class can actually be a native width class to tailwind like say w-8.
Hope this helps.

Related

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.

Asigning CSS property to variable in JavaScript [Polymer]

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.

Using JQuery to change CSS of element with dynamic class

I am trying to change the CSS of an element within a for-loop so that every element in the loop get different CSSes.
for(blablabla.. i++){
icon: myIcon = L.divIcon({
className: 'tempPanel s' + trackers[index].id
})}
This makes every element's class contain 'tempPanel' and 's1' or 's2' or 's3' and so on..
After that i have..
$('.s' + trackers[index].id).css("background-image", "url('data:image/svg+xml;utf8,"+ app6aIcon +"')");
..because i want every element to have the CSS properties of both tempPanel and sX. This however doesnt give the objects a background image. If i change code to..
$('.tempPanel').css("background-image", "url('data:image/svg+xml;utf8,"+ app6aIcon +"')");
.. all the elements will get the same background-image (obviously)..
How can i give elements different background and still apply CSS properties of tempPanel?
It's not entirely clear what your use is but here is a contrived example of how to set the background image of each element with a particular class to a different image provided by some data source. I'm using data attributes on other html elements to store the image urls but you could use an array or an object ....whatever you want really.
Note that this method leaves out the second class altogether and instead uses eq() with the class we already have.
$('.tempPanel').each(function() {
var cur = $('.tempPanel').index($(this));
var url = $('.holder').eq(cur).data('img-url');
$(this).css('background-image', 'url(' + url + ')');
});
.tempPanel {
width: 100px;
height: 100px;
float: left;
margin-left: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="holder" data-img-url="https://placeimg.com/100/100/arch"></div>
<div class="holder" data-img-url="https://placeimg.com/100/100/nature"></div>
<div class="holder" data-img-url="https://placeimg.com/100/100/people"></div>
<br>
<div class="tempPanel"></div>
<div class="tempPanel"></div>
<div class="tempPanel"></div>
I solved it now, and the answer is pretty simple. All I had to do was place the JQuery.css line AFTER the className was given to the element. I also changed className to className: 's'+index instead of 'tempPanel s' + index.
Thank you so much for answering.

Get Actual CSS Property of element if it dynamically added "!important"

I have a Element with the id="somID";
For Example:
Html:
<div id='somID' ></div>
Css :
#somID{ width:500px;height:500px}
and i have a class named : maximize.
So,
.maximize{width:100% !important; height:100% !important; }
Now dynamically i added the class .maximize to my div #somID
And after that i wanna get the width and height of my #somID by calling with its ID like,
$('#somID').width() or .height()
but i want to take the actual height of element that is defined in its ID but i get the .maximize in result not the height or width that is in #somID.
Any buddy have any idea ? That how to retrieve the height of div#somID if it contains .maximize ??
The problem is, there can be many, many selectors that are applied to a given element, with different specificities. There is no API that allows you to request a property from a selector in CSS - it simply wouldn't make much sense.
Having said that, you can create a hack to solve that issue:
function getOriginalDimensions(id) {
var $a = $("<div>", {id:id});
$("body").append($a);
var width = $a.width();
var height = $a.height();
$a.remove();
return {width:width, height:height};
}
console.log(getOriginalDimensions("somID")); // returns {width:500, height:500}
The above works with your example HTML and CSS.
JSFiddle
This basically creates an element with the same ID, appends it to the body, reads the dimensions and deletes it immediately. This is necessary because the div will have no size if it is just kept as a document fragment and not added to the DOM, because the CSS will not get applied.
In theory you could expand this function to make it work with other selectors.
However bear in mind this is a nasty hack and you should reconsider your approach.
A. Make your measurements and save them as .data attributes of the element :
var $el = $('#somID');
$el.data('original_dims', {
height: $el.height(),
width: $el.width()
}
B. Add class that changes the dimensions of the element :
$el.addClass('maximise');
C. Retrive the original dimensions whenever they are needed
var h = $el.data('original_dims').height;
var w = $el.data('original_dims').width;

js style properties returns blank

I am trying to receive the original CSS width value of an object using JavaScript. However, if I use:
var originalWidth = document.getElementById(<idOfObject>).style.width;
It always returns blank. I've also noticed that any property I access using this syntax will return blank. I know for sure that the given element exists, since
alert(document.getElementById(<idOfObject>));
does shows me the right object.
Can anyone help me to solve this problem?
You probably try to get the value which was set in stylesheet, not directly like this:
document.getElementById(<idOfObject>).style.width = '100px';
If you want to get the width of the element you can use innerWidth property:
var width = document.getElementById(<idOfObject>).offsetWidth;
None of the previous answers were right.
The property you are looking for is clientWidth, but not in "style"
document.getElementById('idOfObject').clientWidth;
That will work both on "width" set with external css, style seccion or even inline style="width:80px"
General note: don't use <div width="500"> as it has no effect
The mentioned offsetWidth is the second best choice, but it does not return the exact width set in css, but that width plus border width
Other options like innerWidth that works with window object didn't work for me on divs.
This bizarre issue of realizing style.width not working properly, wasted 2 hours of my precious time :-), hope this answer shorts that time for anyone else in the future.
<div style="width:10%" id="mydiv" >
OR
<div style="width:10px" id="mydiv" >
var mydiv = document.getElementById("mydiv");
var curr_width = mydiv.style.width;
alert(curr_width);
This works for me
I tried it and I can get the value
http://jsfiddle.net/xyd95/
Well, unless the width has no unit
http://jsfiddle.net/xyd95/1/
I believe this will work
function getWidth()
{
x = document.getElementById(<idOfObject>)
return x.offsetWidth;
}

Categories

Resources