Jquery Toggle Content between two specific words in HTML - javascript

I have the following Javascript code to toggle content between -a- & -ea-.
When this runs, I have a "View answer" link in my HTML.
Now, I want to behavior like: between -example- & -endexample- , I should have a "View example" link, between -sample- & -endsample-, I should have a "View Sample" link and so on.
The fiddle https://jsfiddle.net/eoc74009/6/
$(document).ready(funciton(){
initToggleContent();
});
initToggleContent = function(){
var p_content = $(".content").html();
p_content = p_content.replace(new RegExp("-a-","g"),"<div class='hidden toggle-content'>")
p_content = p_content.replace(new RegExp("-ea-","g"),"</div><hr>")
$(".content").html(p_content);
$("<a class='toggle-button'>View Answer</a>").insertBefore(".toggle-content");
$(document).on('click',".toggle-button",function(){
$(this).next(".toggle-content").toggleClass("hidden");
if($(this).html()==="View Answer"){
$(this).html("Hide Answer");
}
else{
$(this).html("View Answer");
}
});
}

You can use this code:
p_content = p_content.replace(/-([^\-]+)-([\s\S]*)-end\1-/gm, function(_, name, content) {
return '<a class="toggle-button" data-name="' + name +
'">View ' + name + '</a>' +
'<span class="hidden toggle-content">' +
content + '</span><hr>';
});
span instead of div because div can't be inside p tag.
Regex explanation:
-([^\-]+)- will match dash, any number of not dashes and a dash
([\s\S]*) will match anything including newline characters
-end\1- will match dash end and prevouisly matched name
parentesis are used as capturing group so you can reference them in replace.
And modifed click handler:
$(document).on('click',".toggle-button",function(){
$(this).next(".toggle-content").toggleClass("hidden");
var name = $(this).data('name');
if($(this).html()==="View " + name){
$(this).html("Hide " + name);
}
else{
$(this).html("View " + name);
}
});
JSFIDDLE

I went a little silly on this and kept iterating an the answer to come up with a more frameworky solution, this allows you to create your own html snippets that look kind of like jsx, and rely's on css checkboxes to toggle the content rather than binding js which can get cumbersome if not managed properly.
https://jsfiddle.net/eoc74009/9/
var
$content = $('.content'),
__id = makeNumberIterator(),
text = $content.html();
// this object holds the bbcode functions
var codes = {
sample: bbcode('sample', function(content, id) {
return (
'<section class="sample">' +
'<input type="checkbox" class="sample-checkbox" id="sample-' + id + '">' +
'<label for="sample-' + id + '" class="sample__label">Sample</label>' +
'<div class="sample__content"><h3>' + content + '</h3></div>' +
'</section>'
);
}),
link: bbcode('a', function(content, id) {
return (
'<section class="toggle">' +
'<input type="checkbox" class="toggle__checkbox" id="toggle-' + id + '">' +
'<label for="toggle-' + id + '" class="toggle__label">Answer</label>' +
'<div class="toggle__content">' + content + '</div>' +
'</section>'
)
})
}
$content.html(replaceWithCodes(text, codes));
/**
* replaceWithCodes
*
* this funtion will call each of the bbcodes functions to replace the content
*
* #param {string} content html content from the page
* #param {Object} codes object of the bbcode functions
*/
function replaceWithCodes(content, codes) {
for (var key in codes) {
content = codes[key](content);
}
return content;
}
/**
* bbcode
*
* this is a factory for a function to replace your -bbcode- with a template
*
* #param {string} code bbcode to find in text without hyphens
* #param {Function} template jsx style function template, recieves content and id
*
* #returns {string} replaced template
*/
function bbcode(code, template) {
return function(input) {
var reg = new RegExp('-' + code + '-([^-]+)-end' + code + '-', 'gm');
return input.replace(reg, function(_, content) {
return template(content, __id());
});
}
}
/**
* makeNumeberIterator
*
* this is a helper function to get a function which returns
* an incrementing number
*
* #param {Number} initial initial value to iterate from
*/
function makeNumberIterator(initial) {
var ii = initial || 0;
return function() {
return ii++;
}
}
* {
box-sizing: border-box;
}
.sample,
.toggle {
margin: 1em 0;
}
input[type=checkbox] {
-webkit-appearance: none;
appearance: none;
}
input[type=checkbox] ~ label {
background: #3cf;
color: white;
padding: .3em 1em;
margin: 1em 0;
}
input[type=checkbox] ~ label:before {
content: "View ";
}
input[type=checkbox] ~ .toggle__content,
input[type=checkbox] ~ .sample__content {
display: none;
padding: 1em;
.3em;
}
input[type=checkbox]:checked ~ label:before {
content: "Hide ";
}
input[type=checkbox]:checked ~ .toggle__content,
input[type=checkbox]:checked ~ .sample__content {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content">
<h2>
Hello my name is bleh!
</h2>
<p>
-a- Happy new year man! How ya doing?! -enda- -sample- something something darkside -endsample-
</p>
</div>

Related

Trouble with script-generated dynamic html element

I developing comment section for my HTMl page. I place it in div container in body section in my page, like that:
<body>
...
<div id='commentsTree'></div>
...
</body>
Commment section generated by script, here it is
function createCommentsTree(commentsData) {
resultHTML = "";
let commentsArray = JSON.parse(commentsData);
//let result = "";
resultHTML = resultHTML + "<ul id='myUL'>";
commentsArray.forEach(element => {
if (element.hasOwnProperty("subordinates")){
resultHTML = resultHTML + "<li>" +
"<span class='caret'></span><textarea class='textFieldRoot'>" + element.content + "</textarea>" +
"<div align='right'>" +
"<button>Save</button>" +
"<button>Answer</button>" +
"<button>Delete</button>" +
"</div>";
createCommentsTreeHyerarchycally(element);
resultHTML = resultHTML + "</li>";
}
else{
resultHTML = resultHTML + "<li>" +
"<textarea class='textField'>" + element.content + "</textarea>" +
"<div align='right'>" +
"<button>Save</button>" +
"<button>Answer</button>" +
"<button>Delete</button>" +
"</div>" +
"</li>";
}
});
resultHTML = resultHTML + "</ul>";
return resultHTML;
}
function createCommentsTreeHyerarchycally(source) {
resultHTML = resultHTML + "<ul class='nested'>";
source.subordinates.forEach(element => {
if (element.hasOwnProperty("subordinates")){
resultHTML = resultHTML + "<li>" +
"<span class='caret'></span><textarea class='textFieldRoot'>" + element.content + "</textarea>" +
"<div align='right'>" +
"<button>Save</button>" +
"<button>Answer</button>" +
"<button>Delete</button>" +
"</div>";
createCommentsTreeHyerarchycally(element);
resultHTML = resultHTML + "</li>";
}
else{
resultHTML = resultHTML + "<li>" +
"<textarea class='textField'>" + element.content + "</textarea>" +
"<div align='right'>" +
"<button>Save</button>" +
"<button>Answer</button>" +
"<button>Delete</button>" +
"</div>" +
"</li>";
}
})
resultHTML = resultHTML + "</ul>";
}
in result i have hyerarchycally comments tree, you can see it on example here
https://jsfiddle.net/Obliterator/wogurs6L/, or, on picture "comment section" added below.
On picture you can see "caret" symbol, looks like black small arrow near textareas, i mark it on picture. When i click it, comment line must unfold, and show subordinate comment lines. You can try it in example here https://jsfiddle.net/Obliterator/wogurs6L/, in this example it works totally correct. But, in my web page, when i click on "caret" symbol, nohing happens, comment line do not unfold. And this is a problem.
For unfold by clicking "caret" symbol i make this script and css:
script:
var toggler = document.getElementsByClassName("caret");
var i;
for (i = 0; i < toggler.length; i++) {
toggler[i].addEventListener("click", function() {
this.parentElement.querySelector(".nested").classList.toggle("active");
this.classList.toggle("caret-down");
});
}
css:
/* Remove default bullets */
ul, #myUL {
list-style-type: none;
}
.textFieldRoot {
position: relative;
left: 15px;
width: 100%;
}
.textField {
position: relative;
width: 100%;
}
/* Remove margins and padding from the parent ul */
#myUL {
margin: 0;
padding: 0;
}
/* Style the caret/arrow */
.caret {
cursor: pointer;
user-select: none; /* Prevent text selection */
position: absolute;
}
/* Create the caret/arrow with a unicode, and style it */
.caret::before {
content: "\25B6";
color: black;
display: inline-block;
margin-right: 6px;
vertical-align: top;
}
/* Rotate the caret/arrow icon when clicked on (using JavaScript) */
.caret-down::before {
transform: rotate(90deg);
}
/* Hide the nested list */
.nested {
display: none;
}
/* Show the nested list when the user clicks on the caret/arrow (with JavaScript) */
.active {
display: block;
}
i add css and script in my page, for which i trying add comment section, that way (treeListScript.js and treeListStyle.css):
<head>
...
<script type="text/javascript" src="http://localhost/testapp/lib/others/treeList/treeListScript.js"></script>
<link rel="stylesheet" href="http://localhost/testapp/lib/others/treeList/treeListStyle.css">
...
</head>
<body>
...
<div id='commentsTree'></div>
...
</body>
i create my web page this way:
var windowTask = window.open("http://localhost/testapp/site/windows/formTask.html", "taskForm");
windowTask.onload = function(){
windowTask.document.getElementById("formTitle").innerText = "Task " + selectedRow.taskID;
windowTask.document.getElementById("taskID").value = selectedRow.taskID;
windowTask.document.getElementById("title").value = selectedRow.title;
windowTask.document.getElementById("status").value = selectedRow.status;
windowTask.document.getElementById("creator").value = selectedRow.creator;
windowTask.document.getElementById("responsible").value = selectedRow.responsible;
windowTask.document.getElementById("description").value = selectedRow.description;
windowTask.document.getElementById("dateCreation").value = selectedRow.dateCreation;
windowTask.document.getElementById("dateStart").value = selectedRow.dateStart;
windowTask.document.getElementById("dateFinish").value = selectedRow.dateFinish;
var comments = getCommentsTree(selectedRow.taskID, 'task');
windowTask.document.getElementById('commentsTree').innerHTML = createCommentsTree(comments);
line windowTask.document.getElementById('commentsTree').innerHTML = createCommentsTree(comments); creates comment section.
So, what i am doing wrong, what i mus do for my unfold fucntional works correct on my web page? If something unclear, ask, i try explain.
I solve problem by myself. Reason is i just incorrect add event handler to the .caretelements, i add it as script in head section, but i need to add it after i generate comment section, this way:
//creating new HTML page +++
var windowTask = window.open("http://localhost/testapp/site/windows/formTask.html", "taskForm");
windowTask.onload = function(){
windowTask.document.getElementById("formTitle").innerText = "Task " + selectedRow.taskID;
windowTask.document.getElementById("taskID").value = selectedRow.taskID;
windowTask.document.getElementById("title").value = selectedRow.title;
windowTask.document.getElementById("status").value = selectedRow.status;
windowTask.document.getElementById("creator").value = selectedRow.creator;
windowTask.document.getElementById("responsible").value = selectedRow.responsible;
windowTask.document.getElementById("description").value = selectedRow.description;
windowTask.document.getElementById("dateCreation").value = selectedRow.dateCreation;
windowTask.document.getElementById("dateStart").value = selectedRow.dateStart;
windowTask.document.getElementById("dateFinish").value = selectedRow.dateFinish;
//creating new HTML page ---
//creating comment section +++
var comments = getCommentsTree(selectedRow.taskID, 'task');
windowTask.document.getElementById('commentsTree').innerHTML = createCommentsTree(comments);
//creating comment section ---
//adding event handler +++
var toggler = windowTask.document.getElementsByClassName("caret");
var i;
for (i = 0; i < toggler.length; i++) {
toggler[i].addEventListener("click", function() {
this.parentElement.querySelector(".nested").classList.toggle("active");
this.classList.toggle("caret-down");
});
}
//adding event handler ---
now everything works fine. If anyone spend some time for my question, thx.

Add value to parseInt object not working

Here is my javascript:
$('#vendorid').change(function(){
var vendno = $(this).val();
var data_String;
var numpo = parseInt($('#numvendpo').val());
data_String = 'vendorid='+vendno;
$.post('ft-vendno.php',data_String,function(data){
var data = jQuery.parseJSON(data);
$('#vendponum').val($('#vendponum').val() + data +'-'+ numpo+1);
});
});
My output is:
As seen in the bottom textbox the last number "-31" should be "-4" (3+1). Whereas it is currently adding it as a string. I can't seem to figure out the problem though.
The top textbox is #numvendpo and the bottom is #vendponum forgive me for my confusing variable names.
When you do:
some_string + numpo + 1
As the first value is a string, you are concatenating values from right to left, so you would first concatenate numpo (converting it to string) to some_string, and then 1, also as a string.
You can fix that making sure the operations are done in the right order, so one option might be to add parenthesis around numpo + 1:
$('#vendponum').val($('#vendponum').val() + data + '-' + (numpo + 1));
You can also do the sum before:
var numpo = parseInt($('#numvendpo').val()) + 1;
Or use template strings:
$('#vendponum').val(`${ $('#vendponum').val() }${ data }-${ numpo + 1 }`);
Here you can see what works and what does not:
const $vendorid = $('#vendorid');
const $numvendpo = $('#numvendpo');
const $outputParenthesis = $('#outputParenthesis');
const $outputBefore = $('#outputBefore');
const $outputTemplate = $('#outputTemplate');
const $outputWrong = $('#outputWrong');
$('#vendorid, #numvendpo').on('input', () => {
const vendno = $vendorid.val();
const numpo = parseInt($numvendpo.val());
if (isNaN(numpo)) {
return;
}
const numpoPlusOne = numpo + 1;
$outputParenthesis.text(vendno + '-' + (numpo + 1));
$outputBefore.text(vendno + '-' + numpoPlusOne);
$outputTemplate.text(`${ vendno }-${ numpo + 1 }`);
$outputWrong.text(vendno + '-' + numpo + 1);
});
body,
input {
font-family: monospace;
}
input {
border: 3px solid black;
padding: 8px;
width: 200px;
}
p {
margin: 8px 0;
}
.label {
display: inline-block;
width: 222px;
text-align: right;
margin-right: 8px;
}
.wrong {
color: red;
}
<input placeholder="Vendor ID" id="vendorid" type="text" />
<input placeholder="Num Vendor PO" id="numvendpo" type="text" />
<p><span class="label">WITH PARENTHESIS: </span><span id="outputParenthesis"></span></p>
<p><span class="label">SUM BEFORE: </span><span id="outputBefore"></span></p>
<p><span class="label">TEMPLATE LITERAL: </span><span id="outputTemplate"></span></p>
<p class="wrong"><span class="label">WRONG: </span><span id="outputWrong"></span></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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>

Moving Javascript variables into Html Table

i found this guide to create a stock ticker.
I tried to change it into an html table, but i'm stuck.
So, i created the table, but i have big problems to divide each variable.
What i want to accomplish is a table with this columns order:
Symbol: CompName
Price: Price
Change: PriceIcon + ChnageInPrice
%: PercentChnageInPrice
What i've accomplished for now it's just this, all the content in one column (because of the variable StockTickerHTML i guess)
Full Code Link
Can you please help me?
var CNames = "^FTSE,FTSEMIB.MI,^IXIC,^N225,^HSI,EURUSD=X";
var flickerAPI = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22" + CNames + "%22)&env=store://datatables.org/alltableswithkeys";
var StockTickerHTML = "";
var StockTickerXML = $.get(flickerAPI, function(xml) {
$(xml).find("quote").each(function () {
Symbol = $(this).attr("symbol");
$(this).find("Name").each(function () {
CompName = $(this).text();
});
$(this).find("LastTradePriceOnly").each(function () {
Price = $(this).text();
});
$(this).find("Change").each(function () {
ChnageInPrice = $(this).text();
});
$(this).find("PercentChange").each(function () {
PercentChnageInPrice = $(this).text();
});
var PriceClass = "GreenText", PriceIcon="up_green";
if(parseFloat(ChnageInPrice) < 0) { PriceClass = "RedText"; PriceIcon="down_red"; }
StockTickerHTML = StockTickerHTML + "<span class='" + PriceClass + "'>";
StockTickerHTML = StockTickerHTML + "<span class='quote'>" + CompName + " </span> ";
StockTickerHTML = StockTickerHTML + parseFloat(Price).toFixed(2) + " ";
StockTickerHTML = StockTickerHTML + "<span class='" + PriceIcon + "'></span>" + parseFloat(Math.abs(ChnageInPrice)).toFixed(2) + " (";
StockTickerHTML = StockTickerHTML + parseFloat( Math.abs(PercentChnageInPrice.split('%')[0])).toFixed(2) + "%)</span> </br>";
});
$("#dvStockTicker").html(StockTickerHTML);
$("#dvStockTicker").jStockTicker({interval: 30, speed: 2});
});
}
One solution could be this :
(see comments in code)
$(window).load(function() {
StockPriceTicker();
setInterval(function() {
StockPriceTicker();
}, 2 * 1000); // <------ we refresh each 2 seconds
});
// we get the table's body where
// the lines will be inserted.
var $body = $('table tbody');
/*
this will be the cache of
our lines, once they are prepared / transformed
as your need, we will join and insert them
in the body of our table.
*/
var Lines = [];
/*
We define a function in charge of creating the HTML
of each row of hour table, and then push them
in the array defined above "Lines".
*/
var addLine = function(symbol, price, change, percent) {
Lines.push('<tr>' +
'<td class="symbol" >' + symbol + '</td>' +
'<td class="price" >' + price + '</td>' +
'<td class="change" >' + change + '</td>' +
'<td class="percent">' + percent + '</td>' +
'</tr>');
};
// this is your function to get data
function StockPriceTicker() {
var Symbol = "",
CompName = "",
Price = "",
ChnageInPrice = "",
PercentChnageInPrice = "";
var CNames = "^FTSE,FTSEMIB.MI,^IXIC,^N225,^HSI,EURUSD=X";
var flickerAPI = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22" + CNames + "%22)&env=store://datatables.org/alltableswithkeys";
var StockTickerXML = $.get(flickerAPI, function(xml) {
$(xml).find("quote").each(function() {
Symbol = $(this).attr("symbol");
$(this).find("Name").each(function() {
CompName = $(this).text();
});
$(this).find("LastTradePriceOnly").each(function() {
Price = $(this).text();
});
$(this).find("Change").each(function() {
ChnageInPrice = $(this).text();
});
$(this).find("PercentChange").each(function() {
PercentChnageInPrice = $(this).text();
});
var PriceClass = "GreenText",
PriceIcon = "up_green";
if (parseFloat(ChnageInPrice) < 0) {
PriceClass = "RedText";
PriceIcon = "down_red";
}
/*
We create the html to be inserted on each xml loop.
- First : prepare and transform as you need
- Last : use the function we define above "addLine";
*/
var htmlSymbol,
htmlPrice,
htmlChange,
htmlPercent;
htmlSymbol = "<span class='" + PriceClass + "'>";
htmlSymbol = htmlSymbol + "<span class='quote'>" + CompName + " </span></span>";
htmlPrice = parseFloat(Price).toFixed(2) + " ";
htmlChange = parseFloat(Math.abs(ChnageInPrice)).toFixed(2) + "<span class='" + PriceIcon + "'></span>";
htmlPercent = parseFloat(Math.abs(PercentChnageInPrice.split('%')[0])).toFixed(2) + "%";
// We use here the function defined above.
addLine(htmlSymbol, htmlPrice, htmlChange, htmlPercent);
});
/*
Once the loop of reading the XML
end, we have pushed all html in the array "Lines".
So now we delete the content of our table's body, and
we fill it with all the lines joined.
*/
$body.empty().html(Lines.join(''));
// we reset the content of Lines for the next interval
Lines = [];
});
}
.GreenText {
color: Green;
}
.RedText {
color: Red;
}
.up_green {
background: url(http://www.codescratcher.com/wp-content/uploads/2014/11/up.gif) no-repeat left center;
padding-left: 10px;
margin-right: 5px;
margin-left: 5px;
}
.down_red {
background: url(http://www.codescratcher.com/wp-content/uploads/2014/11/down.gif) no-repeat left center;
padding-left: 10px;
margin-right: 5px;
margin-left: 5px;
}
table {
border: solid;
border-color: #666;
}
td {
padding: 3px;
}
.symbol {
border: solid 3px #DDD;
}
.price {
border: solid 3px aqua;
}
.change {
border: solid 3px yellow;
}
.percent {
border: solid 3px purple;
}
td.price,
td.change,
td.percent {
text-align: right;
}
tbody tr:nth-child(odd){
background-color:#EEF;
}
tbody tr:nth-child(even){
background-color:#AAA;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<table>
<thead>
<tr>
<th class='symbol'>Symbol</th>
<th class='price'>Price</th>
<th class='change'>Change</th>
<th class='percent'>%</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>

change font size after decimal point

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>

Categories

Resources