Changing CSS Unicode Content Property Dynamically - css

I am setting up a background in a div tag that is a font awesome icon in each row of a table. This icon depends on the object that is being displayed. I tried setting up the code similar to Changing CSS content property dynamically. However, my data-content would be a unicode. I am assigning the values in an angular controller as follows:
if (type) {
if (type.image.includes('fa-hand-o-up')) {
type.background = '\f0a6';
} else if (type.image.includes('fa-wrench')) {
type.background = '\f0ad';
} else if (type.image.includes('fa-star')) {
type.background = '\f005';
}
return type;
}
and then including them in the table as follows:
<td>
<div class="text-center type-wrapper"
data-content="{{::dataItem.type.background}}">
<span class="bold">{{::dataItem.type.name}}</span>
</div>
</td>
However, this just puts 0a6, 0ad, and 005 as the background 'image'. Is there a way to add unicode content dynamically or is the attr(data-xxx) just for plain text?
Also, I tried adding a attr(data-color) for color, but that doesn't seem to work either. Is that also because I am using hex code instead of plain text?

If I got your question correctly...
try prefixing with &#x reference
span:before{
content: attr(data-content);
}
<span data-content="ÿ"></span>
references start with &# and end with ; and the x means that what's used is a hexadecimal value.

This worked for me: https://stackoverflow.com/a/26025865/2077405
Insert in this format, using the \u that, in Javascript, denotes an
Unicode number inside a string literal
$("a").attr ("data-content", "\u25BC");

Related

What CSS should I write in html template to generate a pdf of a particular height & width

I am generating a PDF using nodejs with pdf-creator-node and I got success.
My requirement is I need to generate a PDF with Height X Width = 926px X 1296px.
I don' know what css I should write to generate this dimension pdf.
right now if I set div or body height and widht with above mentioned dimension I am getting 3 pages
this is what I tried
#page {
width: 1296px;
height: 926px;
}
<div
class="parent-div"
style="
width: 1296px;
height: 926px;
background-color: #faf0e6;
border: 1px solid red;
"
></div>
jsPDF is able to use plugins. In order to enable it to print HTML, you have to include certain plugins and therefore have to do the following:
Go to https://github.com/MrRio/jsPDF and download the latest
Version.
Include the following Scripts in your project:
jspdf.js
jspdf.plugin.from_html.js
jspdf.plugin.split_text_to_size.js
jspdf.plugin.standard_fonts_metrics.js
If you want to ignore certain elements, you have to mark them with an ID, which you can then ignore in a special element handler of jsPDF. Therefore your HTML should look like this:
<!DOCTYPE html>
<html>
<body>
<p id="ignorePDF">don't print this to pdf</p>
<div>
<p><font size="3" color="red">print this to pdf</font></p>
</div>
</body>
</html>
Then you use the following JavaScript code to open the created PDF in a PopUp:
var doc = new jsPDF();
var elementHandler = {
#ignorePDF': function (element, renderer) {
return true;
}
};
var source = window.document.getElementsByTagName("body")[0];
doc.fromHTML(
source,
15,
15,
{
'width': 180,'elementHandlers': elementHandler
});
doc.output("dataurlnewwindow");
**For me this created a nice and tidy PDF that only included the line 'print this to pdf'.
Please note that the special element handlers only deal with IDs in the current version, which is also stated in a GitHub Issue. It states:**
Because the matching is done against every element in the node tree, my desire was to make it as fast as possible. In that case, it meant "Only element IDs are matched" The element IDs are still done in jQuery style "#id", but it does not mean that all jQuery selectors are supported.
Therefore replacing '#ignorePDF' with class selectors like '.ignorePDF' did not work for me. Instead you will have to add the same handler for each and every element, which you want to ignore like:
var elementHandler = {
#ignoreElement': function (element, renderer) {
return true;
},
#anotherIdToBeIgnored': function (element, renderer) {
return true;
}
};
From the examples it is also stated that it is possible to select tags like 'a' or 'li'. That might be a little bit too unrestrictive for the most use cases though:
We support special element handlers. Register them with a jQuery-style ID selector for either ID or node name. ("#iAmID", "div", "span" etc.) There is no support for any other type of selectors (class, of the compound) at this time.
One very important thing to add is that you lose all your style information (CSS). Luckily jsPDF is able to nicely format h1, h2, h3, etc., which was enough for my purposes. Additionally, it will only print text within text nodes, which means that it will not print the values of textareas and the like. Example:
<body>
<ul>
<!-- This is printed as the element contains a textnode -->
<li>Print me!</li>
</ul>
<div>
<!-- This is not printed because jsPDF doesn't deal with the value attribute -->
<input type="textarea" value="Please print me, too!">
</div>
</body>

Custom styling of text substrings in dynamic Angular templates

Is it possible to apply styles like bold / italic or both together in angular 6 by just having starting and ending point of the text while creating or after creating the components dynamically ? Right now I'm able to apply styles for the whole component but i wanted to apply style only for a particular text in the element and the length of the text will be from JSON.
Please find stackblitz implementation here.
Actual result should apply the style to text based on the offset and length
Yes, you should be able to achieve this with a conditional ngStyle statement, based on the length of the text string, or other criteria. E.g. apply bold and italic styling if your text string is longer than 20 characters:
<div [ngStyle]="textString.length > 20 && {'font-weight': 'bold', 'font-style': 'italic'}">{{textString}}</div>
Further information here and here is an example on Stackblitz.
Alternatively you can apply ngClass conditionally in the same way, and have your custom styling in your CSS file.
Method 1 - Slice Pipe
If you want to add styling based on character positions within some text, rather than the overall length of some text, and you want to do this purely in your HTML template, you could achieve this with the slice pipe.
I've put an example of how this could be applied below and on Stackblitz. The HTML markup is horrible, and line breaks must not be used in the code because these introduce unwanted spaces into the rendered text, but I believe it covers what you're asking for:
For a single highlight:
TS:
singleString = 'London Kings Cross Station';
highlightStart = 3;
highlightLength = 5;
HTML:
<ng-container>{{singleString | slice:0:highlightStart}}</ng-container>
<span class="styled_text">{{singleString | slice:highlightStart:highlightStart+highlightLength}}</span>
<ng-container>{{singleString | slice:highlightStart+highlightLength:singleString.length}}</ng-container>
For multiple highlights:
TS:
textStrings = ['London Kings Cross', 'Bristol Temple Meads'];
stylePositions = [[3,3],[15,3]]; // Start position and length of sections to be styled
HTML:
<ul>
<li *ngFor="let textString of textStrings">
<ng-container *ngFor="let stylePosition of stylePositions; index as i">
<ng-container *ngIf="i==0">{{textString | slice:0:stylePositions[0][0]}}</ng-container><ng-container *ngIf="i!=0">{{textString | slice:stylePositions[i-1][0]+stylePositions[i-1][1]:stylePositions[i][0]}}</ng-container><span class="styled_text">{{textString | slice:stylePositions[i][0]:stylePositions[i][0]+stylePositions[i][1]}}</span><ng-container *ngIf="i==stylePositions.length-1">{{textString | slice:stylePositions[i][0]+stylePositions[i][1]:textString.length}}</ng-container>
</ng-container>
</li>
</ul>
CSS:
.styled_text {
font-weight: bold;
font-style: italic;
color: #ff0000;
}
Method 2 - Inner HTML
A different approach would be to apply the same principle, but use a function to break your string into sections and then pass this to a div in your template using innerHTML - see below and this Stackblitz.
Please note that for this to work, you must also include a custom pipe to declare the HTML as safe for Angular to render with styling. This is also included in the Stackblitz, with more details here.
styleText(string){
let styledText= '';
for (let i = 0; i < this.stylePositions.length; i++) {
if(i==0){
styledText+=string.substring(0, this.stylePositions[i][0]);
} else {
styledText+=string.substring(this.stylePositions[i-1][0]+this.stylePositions[i-1][1],this.stylePositions[i][0]);
}
styledText+='<span style="color:#ff0000">'+string.substring(this.stylePositions[i][0],this.stylePositions[i][0]+this.stylePositions[i][1])+'</span>';
if(i==this.stylePositions.length-1){
styledText+=string.substring(this.stylePositions[i][0]+this.stylePositions[i][1],string.length);
}
}
return styledText;
}

What effect does \f have when applied to css?

I am reading the code from Font-Awesome, which is a library that (from what I understand) overwrites parts of Bootstrap to modify some of the code.
There is a class called fa-twitter, created in Font-Awesome:
.fa-twitter:before {
content: "\f099";
}
I do not understand what \f is doing in this situation, and where the numbers "099" are being used. I have tried searching Font-Awesome on Github, thinking perhaps .fa-twitter is defined elsewhere, or something the numbers could be used in, but I haven't found anything so far.
It's not \f that matters. It's Unicode character code.
\f099 means It's not literal "f099" but Unicode value of "f099"
Table itself
Example:
#first:after {
content: "\0178"
}
#second:after {
content: "0178"
}
With "\": <i id="first"></i>
<br/>Without "\": <i id="second"></i>
It's not 'f', it's the content that's important:
If you have code like this:
<p class="email">myemail#gmail.com</p>
You'll just get the email address: myemail#gmail.com.
But if you add this in the CSS:
.email:before {
content: "Email: "
}
You'll get Email: myemail#gmail.com without making any changes to the HTML.
In this case, it's adding a symbol, indicated by the code F099. In other words, the twitter bird:

Attach an image to any word

I'd like to attach images to specific words but cannot find the right CSS selector to do so.
I have a portion of my site which displays data as it's pulled from a database, so adding classes or id's to certain words is not an option for me. I need the css to simply display a background image wherever that word (or in this case, name) is found on the page.
For example, in the following (which is pulled from a database):
<td class="data1"><font face="Verdana, Arial, Helvetica, sans-serif" size="1">Patrick</font></td>
I would like to add a background image where the name Patrick is found.
I tried variations of,
td[.table1 *='Parick'] {
background-image:url(../images/accept.png);
but that didn't get me anywhere. And since it's not in a <span> or <div> or even a link, I can't figure it out. If you have any ideas or a jQuery workaround, please let me know. Thanks!
If you can guarantee the names only appear as the only text nodes in elements, you can use a simple jQuery selector...
$(':contains("Patrick")').addClass('name');
jsFiddle.
If there may be surrounding whitespace and/or the search should be case insensitive, try...
$('*').filter(function() {
return $.trim($(this).text()).toLowerCase() == 'patrick';
}).addClass('name');
jsFiddle.
If you need to find the name anywhere in any text node and then you need to wrap it with an element, try...
$('*').contents().filter(function() {
return this.nodeType == 3;
}).each(function() {
var node = this;
this.data.replace(/\bPatrick\b/i, function(all, offset) {
var chunk = node.splitText(offset);
chunk.data = chunk.data.substr(all.length);
var span = $('<span />', {
'class': 'name',
text: all
});
$(node).after(span);
});
});​
jsFiddle.
I would recommend using the third example.

CSS text-transform capitalize on all caps

Here is my HTML:
small caps &
ALL CAPS
Here is my CSS:
.link {text-transform: capitalize;}
The output is:
Small Caps & ALL CAPS
and I want the output to be:
Small Caps & All Caps
Any ideas?
You can almost do it with:
.link {
text-transform: lowercase;
}
.link:first-letter,
.link:first-line {
text-transform: uppercase;
}
It will give you the output:
Small Caps
All Caps
There is no way to do this with CSS, you could use PHP or Javascript for this.
PHP example:
$text = "ALL CAPS";
$text = ucwords(strtolower($text)); // All Caps
jQuery example (it's a plugin now!):
// Uppercase every first letter of a word
jQuery.fn.ucwords = function() {
return this.each(function(){
var val = $(this).text(), newVal = '';
val = val.split(' ');
for(var c=0; c < val.length; c++) {
newVal += val[c].substring(0,1).toUpperCase() + val[c].substring(1,val[c].length) + (c+1==val.length ? '' : ' ');
}
$(this).text(newVal);
});
}
$('a.link').ucwords();​
Convert with JavaScript using .toLowerCase() and capitalize would do the rest.
Interesting question!
capitalize transforms every first letter of a word to uppercase, but it does not transform the other letters to lowercase. Not even the :first-letter pseudo-class will cut it (because it applies to the first letter of each element, not each word), and I can't see a way of combining lowercase and capitalize to get the desired outcome.
So as far as I can see, this is indeed impossible to do with CSS.
#Harmen shows good-looking PHP and jQuery workarounds in his answer.
I'd like to sugest a pure CSS solution that is more useful than the first letter solution presented but is also very similar.
.link {
text-transform: lowercase;
display: inline-block;
}
.link::first-line {
text-transform: capitalize;
}
<div class="link">HELLO WORLD!</div>
<p class="link">HELLO WORLD!</p>
HELLO WORLD! ( now working! )
Although this is limited to the first line it may be useful for more use cases than the first letter solution since it applies capitalization to the whole line and not only the first word. (all words in the first line)
In the OP's specific case this could have solved it.
Notes: As mentioned in the first letter solution comments, the order of the CSS rules is important! Also note that I changed the <a> tag for a <div> tag because for some reason the pseudo-element ::first-line doesn't work with <a> tags natively but either <div> or <p> are fine.
EDIT: the <a> element will work if display: inline-block; is added to the .link class. Thanks to Dave Land for spotting that!
New Note: if the text wraps it will loose the capitalization because it is now in fact on the second line (first line is still ok).
JavaScript:
var links = document.getElementsByClassName("link");
for (var i = 0; i < links.length; i++) {
links[i].innerHTML = links[i].innerHTML.toLowerCase();
}
CSS:
.link { text-transform: capitalize; }
What Khan "ended up doing" (which is cleaner and worked for me) is down in the comments of the post marked as the answer.
captialize only effects the first letter of the word. http://www.w3.org/TR/CSS21/text.html#propdef-text-transform
You can do it with css first-letter!
eg I wanted it for the Menu:
a {display:inline-block; text-transorm:uppercase;}
a::first-letter {font-size:50px;}
It only runs with block elements - therefore the inline-block!
May be useful for java and jstl.
Initialize variable with localized message.
After that it is possible to use it in jstl toLowerCase function.
Transform with CSS.
In JSP
1.
<fmt:message key="some.key" var="item"/>
2.
<div class="content">
${fn:toLowerCase(item)}
</div>
In CSS
3.
.content {
text-transform:capitalize;
}
If the data is coming from a database, as in my case, you can lower it before sending it to a select list/drop down list. Shame you can't do it in CSS.
After researching a lot I found jquery function/expression to change text in first letter in uppercase only, I modify that code accordingly to make it workable for input field. When you will write something in input field and then move to another filed or element, the text of that field will change with 1st-letter capitalization only. No matter user type text in complete lower or upper case capitalization:
Follow this code:
Step-1: Call jquery library in html head:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
Step-2: Write code to change text of input fields:
<script>
$(document).ready(function(){
$("#edit-submitted-first-name,#edit-submitted-last-name,#edit-submitted-company-name, #edit-submitted-city").focusout(function(){
var str=$(this).val();
str = str.toLowerCase().replace(/\b[a-z]/g, function(letter) {
return letter.toUpperCase();
});
$(this).val(str);
});});
</script>
Step-3: Create HTML input fields with same id's you use in jquery code like:
<input type="text" id="edit-submitted-first-name" name="field name">
The id of this input field is: edit-submitted-first-name (It using in jquery code in step-2)
**Result:
Make sure the text will change after you move your focus from that input field at another element. Because we using focus out event of jquery here.
Result should like this: User Type: "thank you" it will change with "Thank You".
**
Best of luck
The PHP solution, in backend:
$string = 'UPPERCASE';
$lowercase = strtolower($string);
echo ucwords($lowercase);
I know this is a late response but if you want to compare the performance of various solutions I have a jsPerf that I created.
Regex solutions are the fastest for sure.
Here is the jsPerf: https://jsperf.com/capitalize-jwaz
There are 2 regex solutions.
The first one uses/\b[a-z]/g. Word boundary will capital words such as non-disclosure to Non-Disclosure.
If you only want to capitalize letters that are preceded by a space then use the second regex
/(^[a-z]|\s[a-z])/g
if you are using jQuery; this is one a way to do it:
$('.link').each(function() {
$(this).css('text-transform','capitalize').text($(this).text().toLowerCase());
});
Here is an easier to read version doing the same thing:
//Iterate all the elements in jQuery object
$('.link').each(function() {
//get text from element and make it lower-case
var string = $(this).text().toLowerCase();
//set element text to the new string that is lower-case
$(this).text(string);
//set the css to capitalize
$(this).css('text-transform','capitalize');
});
Demo
all wrong it does exist --> font-variant: small-caps;
text-transform:capitalize; just the first letter cap

Resources