change font size after decimal point - javascript

I am working with an Opencart E-Commerce website, I need to customize product price font size,
for example:
product price: $ 250.50 i need to set font size for $ = 16px; 250 = 22px; .50 = 14px;
How can I set different font sizes for a single amount..???
this s my dynamic php code that display price text to my product page:
<span class="price"><?php echo $product['price']; ?></span>
my product list page not a single product with price, there is a lots of product with price list.
thanks for any help, if anybody asked the same question before here, please share with me those links...

$.each($('.price'), function(){
var price = $(this).html();
$(this).html(price.replace(/(\D*)(\d*\.)(\d*)/,'<span style="font-size:16px;">$1</span><span style="font-size:22px;">$2</span><span style="font-size:14px;">$3</span>'));
});
http://jsfiddle.net/gr8x5/10/

Here's a quick and dirty example:
<html>
<head>
<style>
.dollar_sign { font-size: 16px; }
.dollars { font-size: 22px; }
.cents { font-size: 14px; }
</style>
</head>
<body>
<?
$product = array('price' => '245.50');
$part = explode('.', $product['price']);
?>
<span class="dollar_sign">$</span><span class="dollars"><?= $part[0] ?></span>.<span class="cents"><?= $part[1] ?></span>
</body>
</html>

Try this code
var pri = $(".price").text();
var sig = pri.split(" ");
var dol_smbl = "<span style='font-size:16px;'>" + sig[0] + "</span>";
var digits = sig[1].split(".");
befr_dec = "<span style='font-size:22px;'>" + digits[0] + "</span>";
aftr_dec = "<span style='font-size:14px;'>." + digits[1] + "</span>";
$(".price").html(dol_smbl + " " + befr_dec + aftr_dec);

Can be beautifully done with a little css and regex. See this fiddle
the HTML :
<span class="price">$250.50</span>
the css :
.currency { font-size:16px; }
.number { font-size:22px; }
.decimal { font-size:14px; }
the javascript :
var price = $('span.price').text();
var pArry = price.match(/^(\$)(\d+)(\.\d+)?/);
var new_span = $(
'<span class="currency">' + pArry[1] + '</span>' +
'<span class="number">' + pArry[2] + '</span>' +
'<span class="decimal">' + pArry[3] + '</span>');
$('span.price').replaceWith(new_span);
Done

Try like this
var my_price = $(".price").text();
var dol_smbl = "<span style='font-size:16px;'>"+my_price[0]+"</span>";
var price = split(" ",my_price);
var price_arr = split('.',price[1]);
befr_dec = "<span style='font-size:22px;'>"+price_arr[0]+"</span>";
aftr_dec = "<span style='font-size:14px;'>."+price_arr[1]+"</span>";
$(".price").html(dol_smbl + " " + befr_dec + aftr_dec);

The easiest way would be to split up that var? Look at the php function explode().
http://php.net/manual/de/function.explode.php

You can try this generic approach
$('.price').each(function () {
var $this = $(this),
txt = $this.text(),
splt = txt.split('.'),
spltFirst = splt.pop(),
spn3 = $('<span/>', {
text: spltFirst,
'class': 'font-small'
}),
spltSecond = splt.pop(),
spn1 = $('<span/>', {
text: spltSecond.substring(0, spltSecond.lastIndexOf('$') + 1),
'class': 'font-medium'
}),
spn2 = $('<span/>', {
text: spltSecond.substring(spltSecond.lastIndexOf('$') + 1) + '.',
'class': 'font-big'
});
$this.text('');
$this.append(spn1).append(spn2).append(spn3);
});
Check Fiddle

Use different span element for those three different segments and set class for them individually to assign different font styles. Basically spans are inline element, so you dont need to worry about its placement.
For example:
After rendering your markup should be like this,
<span class="price">
<span class="currencySymbol">$</span>
<span class="amt1">250</span>
<span class="amt2">.50</span>
</span>
then in CSS:
.currencySymbol{ font-size:16px; }
.amt1{ font-size:22px; }
.amt2{ font-size:14px; }

A possible simple dynamic way using only split().
This will wrap decimals in a <small> tag on each element having a class format .
document.querySelectorAll(".format").forEach((e) => {
let txt = e.innerHTML.split(".")
e.innerHTML = txt[0] + ".<small>" + txt[1] + "</small>"
})
.format {font-size:3rem}
small {font-size:1.4rem}
<div class="format">34454.545432</div>
<div class="format">0.0000463533</div>
<div class="format"><mark>Hello</mark> -8765.9876</div>

Related

Javascript: Different background color for different div's

I have some troubles with javascript app to manage meetings. I have three levels of importance: 'Important', 'Medium', 'No important' and I want change background-color for them. 'Important' - red color, 'Medium' - yellow and 'No important'-green. I try to hold in content variable string from html and then compare this value with if,else if statement, but it still doesn't work. Do you have some advices?
main.js
function fetchMeetings(){
var meetings = JSON.parse(localStorage.getItem('meetings'));
var meetingsResults = document.getElementById('meetingsResults');
// Build output
meetingsResults.innerHTML = '';
for(var i = 0; i < meetings.length; i++){
var date = meetings[i].date;
var person = meetings[i].person;
var purpose = meetings[i].purpose;
var warning = meetings[i].warning;
meetingsResults.innerHTML += '<div class="mettingDiv">'+
'<h3>'+date+'</h3>'+
'<h3>'+person+'</h3>' +
'<h3>'+purpose+'</h3>'+
'<h3 class="importance">'+warning+'</h3>'+
' <a onclick="deleteMeeting(\''+purpose+'\')" class="btn btn-danger" href="#">Delete</a> ' +
'</div>';
}
var content= document.getElementsByClassName("importance").innerHTML;
if(content == 'Important'){
$('.mettingDiv').css('background-color', '#c00100');
}
else if(content == 'Medium'){
$('.mettingDiv').css('background-color', '#fbff30');
}
else if(content == 'No important'){
$('.mettingDiv').css('background-color', '#85ff63');
}
}
github
live app
Ok, I tried to add additional class name to div element, but class name is still the same, code:
meetingsResults.innerHTML += '<div id="div1" class="mettingDiv">'+
'<h3>'+date+'</h3>'+
'<h3>'+person+'</h3>' +
'<h3>'+purpose+'</h3>'+
'<h3 class="importance">'+warning+'</h3>'+
' <a onclick="deleteMeeting(\''+purpose+'\')" class="btn btn-danger" href="#">Delete</a> ' +
'</div>';
}
var content= document.getElementsByClassName("importance").innerHTML;
var d = document.getElementById("div1");
if(content == 'Important'){
d.className += " important";
}
Try this
meetingsResults.innerHTML += '<div class="mettingDiv ' + warning + '">'+ ...
this will result in <div class="mettingDiv Important"..., <div class="mettingDiv No important" ... and then add CSS
.Important { background-color: #c00100; }
.Medium { background-color: #fbff30; }
.No.important { background-color: #85ff63; }

apply diffrent css for text separated by comma inside <div>

i am trying to change color for text which are separated by comma(','). i cant use any other tag to separate these. is that possible by jQuery or by css?
<div data-value="ABCD,XYZ" style="padding-left: 12px; padding-right: 12px;">ABCD,XYZ</div>
<div data-value="ABCD,XYZ" style="padding-left: 12px; padding-right: 12px;">cdE,hhhh</div>
Created a fiddle for you
var colorArr = ['red', 'green'];
$( "[data-value='ABCD,XYZ']" ).each ( function(){
var valueArr = $( this ).html().split( "," );
console.log( valueArr );
for (var counter = 0; counter < valueArr.length; counter++ )
{
valueArr[ counter ] = "<span style='color:" + colorArr[ counter ] + "'>" + valueArr[ counter ] + "</span>";
}
console.log( valueArr );
$( this ).html( valueArr.join("") );
} );
Im not sure if you are referring to the innerHTML or the tag's value.. either way. I was not able to test this due to browser issues.
$('div').each(function(){
var textArray = $(this).html().split(',');
var html = '';
for(var i = 0; i < textArray.length; i++) {
html += '<span style="color: #12345' + i + '">' + textArray[i] + '</span>';
}
$(this).html(html);
}
This is what I would do:
$("[data-value]").each(function(){
var words = $(this).text().split(",");
$(this).text("");
for(var i=0; i< words.length; i++){
var r = Math.floor((Math.random() * 255) + 1);
var g = Math.floor((Math.random() * 255) + 1);
var b = Math.floor((Math.random() * 255) + 1);
$(this).append("<span style='color:rgb("+r+","+g+","+b+")'>"+words[i]+ ((i< words.length-1) ? ",":"")+"</span>");
}
});
Here is the JSFiddle demo
The code randomly generates colors and sets a different color for each word.
You can use
:contains() css3 selector
Check this out
$(document).ready(function(){
$('div').each(function(){
var text = $(this).text();
var array = text.split(',');
var html = array[0] + ',<span style="color:red">' + array[1] + '</span>';
$(this).html(html);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-value="ABCD,XYZ" style="padding-left: 12px; padding-right: 12px;">ABCD,XYZ</div>
<div data-value="ABCD,XYZ" style="padding-left: 12px; padding-right: 12px;">cdE,hhhh</div>
Since you are using attr data use .data() to find your elements
$('div').data('value','ABCD,XYZ').each(function(i,vi){
var arrVi = vi.innerText.split(',');
var html = '';
arrVi.forEach(function(vj,j){
html += '<span style="color: green">' + vj + '</span>';
});
vi.innerHTML= html;
})
Change the code to the ways it suits you better.
If you can't change the html code at all you can use :before and :after pseudo selectors.
Split the text by ,.
Set attributes for each of them.
Set content to :before and :after by the attributes
Style those pseudo elements.
This solution will works only with 1 comma separation.
[].forEach.call(document.querySelectorAll('div'), function(item) {
// check if there is a , in the text
if (item.innerText.indexOf(',') > -1) {
var texts = item.innerText.split(',');
item.setAttribute('data-text1', texts[0]);
item.setAttribute('data-text2', texts[1]);
item.innerHTML = ',';
}
});
div:before {
content:attr(data-text1);
color:red;
}
div:after {
content:attr(data-text2);
color:yellow;
}
<div data-value="ABCD,XYZ" style="padding-left: 12px; padding-right: 12px;">ABCD,XYZ</div>
<div data-value="ABCD,XYZ" style="padding-left: 12px; padding-right: 12px;">cdE,hhhh</div>

getJSON JSON Array - Search Functionality Crashing Client

I'm running into a problem when trying to add in the search functionality, showList().
It seems to bog down the client so much that Chrome wants to kill the page each time I type into the input field. I'm clearly a novice JS writer, so could I be running an infinite loop somewhere I don't see? Also, any advice to get the search functionality working properly would be hugely appreciated. I don't think I'm using the correct selectors below for the show/hide if statement, but I can't think what else to use.
$(document).ready(function(){
showList();
searchBar();
});
function showList() {
$("#show-records").click(function(){
$.getJSON("data.json", function(data){
var json = data;
$("show-list").append("<table class='specialists'>")
for(var i = 0; i < json.length; i++) {
var obj = json[i],
tableFormat = "</td><td>";
$("#show-list").append("<tr><td class=1>" +
obj.FIELD1 + tableFormat +
obj.FIELD2 + tableFormat +
obj.FIELD3 + tableFormat +
obj.FIELD4 + tableFormat +
obj.FIELD5 + tableFormat +
obj.FIELD6 + tableFormat +
obj.FIELD7 + tableFormat +
obj.FIELD8 + "</td></tr>");
$("show-list").append("</table>");
}
//end getJSON inner function
});
//end click function
});
//end showList()
};
function searchBar() {
//AJAX getJSON
$.getJSON("data.json", function(data){
//gathering json Data, sticking it into var json
var json = data;
for(var i = 0; i < json.length; i++) {
//putting the json objects into var obj
var obj = json[i];
function contains(text_one, text_two) {
if (text_one.indexOf(text_two) != -1)
return true;
}
//whenever anything is entered into search bar...
$('#search').keyup(function(obj) {
//grab the search bar content values and...
var searchEntry = $(this).val().toLowerCase();
//grab each td and check to see if it contains the same contents as var searchEntry - if they dont match, hide; otherwise show
$("td").each(function() {
if (!contains($(this).text().toLowerCase(), searchEntry)) {
$(this).hide(400);
} else {
$(this).show(400);
};
})
})
}
});
};
body {
background-color: lightblue;
}
tr:first-child {
font-weight: bold;
}
td {
padding: 3px;
/*margin: 10px;*/
text-align: center;
}
td:nth-child(6) {
padding-left: 50px;
}
td:nth-child(7) {
padding-left: 10px;
padding-right: 10px;
}
#filter-count {
font-size: 12px;
}
<html>
<head>
<script language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script language="javascript" src="process.js"></script>
<link rel="stylesheet" type="text/css" href="./mystyle.css">
</head>
<body>
<a href="#" id='show-records'>Show Records</a><br>
<label id="searchBar">Search: <input id="search" placeholder="Enter Specialist Name"></label>
<span id="search-count"></span>
<div id="show-list"></div>
</body>
</html>
Problem appears to be that you can't treat append as if it was a text editor and you are writing html.
Anything that gets inserted needs to be a proper element ... not a start tag, then some text...then a close tag.
We can however modify your code slightly to produce html strings and then add that at the end
$.getJSON("data.json", function(data){
var json = data;
var html="<table class='specialists'>")
for(var i = 0; i < json.length; i++) {
var obj = json[i],
tableFormat = "</td><td>";
html+= "<tr><td class=1>" +
obj.FIELD1 + tableFormat +
obj.FIELD2 + tableFormat +
obj.FIELD3 + tableFormat +
obj.FIELD4 + tableFormat +
obj.FIELD5 + tableFormat +
obj.FIELD6 + tableFormat +
obj.FIELD7 + tableFormat +
obj.FIELD8 + "</td></tr>";
}
html+= '</table>';
$("#show-list").html(html);
//end getJSON inner function
});

How do I specify where a span will be placed in a extjs grid?

I'm trying to understand the code I edited.
So I created the following variable
var headerPlaceHolderComponent = '()';
and placed it in the function below
formatTitle: function (containerWidth, containerNameTitle, aggregationTitle) {
// one character approximates to 6 pixels. So, dividing by 5.5
var maxCharacters = Math.ceil(containerWidth / 5.5);
var combinedTitle = containerNameTitle + aggregationTitle;
if (combinedTitle.length > maxCharacters) {
var numberOfCharsToTruncate = maxCharacters - combinedTitle.length;
aggregationTitle = aggregationTitle.replace(aggregationTitle.slice(numberOfCharsToTruncate), '...');
}
var formattedContainerNameTitle = '<span class="conatiner-name-title">' + containerNameTitle + '</span>';
var formattedAggregationTitle = '(<span class="aggregation-title-style-in-grid">' + aggregationTitle + '</span>)';
var headerPlaceHolderComponent = '(<span class="header-placeholder"></span>)';
var formattedCombinedTitle = aggregationTitle.length > 0 ? formattedContainerNameTitle + ' ' + formattedAggregationTitle + headerPlaceHolderComponent
: formattedContainerNameTitle + headerPlaceHolderComponent ;
return formattedCombinedTitle;
},
Currently the Span that I created renders out in HTML within the following span.
<span class="x-panel-header-text x-panel-header-text-default-framed" id="ext-gen1419">
<span id="ext-gen1525" class="header-placeholder"></span> <!--My Span -->
</span>
I would like my span to render within this div instead:
So my final rendered coded will look like this:
<div class="x-component x-box-item x-component-default" id="component-1196" role="heading">
<span id="ext-gen1525" class="header-placeholder"></span> <!--My Span -->
</div>
How can I specify where in the HTML my span will render?

Creating and Adding content dynamically

I'm creating some ul and span tags dynamically. Now, I'm trying to add content dynamically as well through a click function. The tags gets created inside a ul but the content doesn't get inserted. Here is the code for it:
<div class="main"></div>
<div class="content-list"><ul class="information"> </ul></div>
Here's the Javascript with the function and the listener:
var $contentHandler = $(".content-list");
var $mainHandler = $(".main");
var $infoHandler = $(".information");
var circleCounter = 1;
$mainHandler.click(function() {
var htmlString = "<li class='" + circleCounter + "'> <span class='circle-color'> var color = <div class='circle-color-input' contentEditable autocorrect='off'> type a color</div> ; </span> <br> <span class='circle-radius'> This is supposed to change </span> <br> <span class='circle'> This is supposed to change </span> </li>"
$infoHandler.append(htmlString);
updateList();
circleCounter++;
});
function updateList() {
var listItems = $('.information').find('li#' + circleCounter);
var len = circleCounter;
for (var i = 0; i < len; i++) {
//We create one reference. This makes looking for one element more effective. Unless we need to search for a particular element
var currentItem = circles[i];
var updateStringRadius = "var radius = " + circleCounter + ";";
var updateStringCircle = "circle (" + circleCounter + " ," + circleCounter + ", radius)";
//This is the div Item for the particular div of each element
var divItem = $(listItems[i]);
var radiusItem = divItem.find("span.circle-radius");
var circleItem = divItem.find("span.circle");
radiusItem.text(updateStringRadius);
circleItem.text(updateStringCircle);
// divItem.text(updateString);
var $circleRadiusHandler = $(".circle-radius");
}
}
Any suggestions in how to make it work. Here's a JSFiddle for that:
http://jsfiddle.net/mauricioSanchez/wL6Np/1/
Thank you kindly,
You just need to change:
var listItems = $('.information').find('li#' + circleCounter);//this searches by id
//To:
var listItems = $('.information').find('li.' + circleCounter);//this searches by class`
//And remove:
var currentItem = circles[i];
Why are you trying to edit your HTML after you've defined it? Why not use a template like this:
var listItemClass = 'someclass',
typeOfColor = 'somecolor',
radiusOne = 'someradius',
radiusTwo = 'anotherradius';
var listItem = "<li class='{0}'> \
<span class='circle-color'> var color = \
<div class='circle-color-input' contentEditable autocorrect='off'> {1}</div> ; \
</span> \
<br> \
<span class='circle-radius'>{2}</span> \
<br> \
<span class='circle'>{3}</span> \
</li>";
listItem.format(listItemClass, typeOfColor, radiusOne, radiusTwo);
With the following format definition:
String.prototype.format = String.prototype.f = function () {
var s = this,
i = arguments.length;
while (i--) {
s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
}
return s;
};
This way, you don't have to worry about finding certain elements within your predefined structure after the fact. You're just replacing certain parts with whatever you specify.

Categories

Resources