Change color every other row with $.each - css

I am making a golf leaderboard and want to change the color on every other row to be slightly grey... How do I do that?
Here is how I get the leaderboard using ajax:
$.get("http://mypage.com/json/getleaderboard.php", function(data) {
var output = '';
output += '<li class="leaderboard-head"><span class="leaderboard-head-placement"> </span><span class="leaderboard-name tr" key="name">Name</span><span class="leaderboard-head-points">P</span></li>';
$.each(data, function (i, val) {
output += '<li><span class="leaderboard-placement">' + val.placement + '</span><span class="leaderboard-name">' + val.name + '</span><span class="leaderboard-points">' + val.points + '</span></li>';
});
$('#leaderboardList').append(output).listview('refresh');
}, "json");
hoping for help and thanks in advance :-)

You can use the nth-child selector. e.g.
<ul class="leaderboard">
<li class="leaderboard-head">1</li>
<li class="leaderboard-head">2</li>
<li class="leaderboard-head">3</li>
<li class="leaderboard-head">4</li>
<li class="leaderboard-head">5</li>
<li class="leaderboard-head">6</li>
</ul>
CSS
.leaderboard-head:nth-child(odd){ // Odd/Even according to your requirements
background-color: gray;
}
Note that this will only work in CSS3 compatible browsers. For others you can use :
$(".leaderboard").children(":nth-child(odd)").each(function(){ // Odd/Even according to your requirements
$(this).css("background", "gray");
});
FIDDLE
You can remove the css/jquery and it will still work.

Simple, you use CSS and do (assuming there is a class leaderboard-entry):
li.leaderboard-entry {
background-color: #efefef;
}
li.leaderboard-entry:nth-child(even) {
background-color: #afafaf;
}
No JavaScript required.
On a more general note, your code should read
$.get("http://mypage.com/json/getleaderboard.php")
.done(function(data) {
$('<li class="leaderboard-head">' +
'<span class="leaderboard-head-placement"> </span>' +
'<span class="leaderboard-name tr" key="name">Name</span>' +
'<span class="leaderboard-head-points">P</span>' +
'</li>'
).appendTo('#leaderboardList');
$.each(data, function (i, val) {
$('<li class="leaderboard-entry">')
.append($('<span class="leaderboard-placement">', {text: val.placement}))
.append($('<span class="leaderboard-name">', {text: val.name}))
.append($('<span class="leaderboard-points">', {text: val.points}))
.appendTo('#leaderboardList');
});
$('#leaderboardList').listview('refresh');
});
Don't create HTML by concatenating arbitrary strings. This is the single source of cross site scripting vulnerabilities (and blown markup).
Also, declaring the request type ("json") in jQuery is superfluous if the server sends JSON and sets the correct Content-Type header.

if you sway to do using jquery rather than css (good one)
$.get("http://mypage.com/json/getleaderboard.php", function(data) {
var output = '';
output += '<li class="leaderboard-head"><span class="leaderboard-head-placement"> </span><span class="leaderboard-name tr" key="name">Name</span><span class="leaderboard-head-points">P</span></li>';
$.each(data, function (i, val) {
var color_style_class = 'blue';
if (i % 2 == 0)
{
color_style_class = 'green';
}
else
{
color_style_class = 'red';
}
output += '<li><span class="leaderboard-placement ' + color_style_class + '">' + val.placement + '</span><span class="leaderboard-name">' + val.name + '</span><span class="leaderboard-points">' + val.points + '</span></li>';
});
$('#leaderboardList').append(output).listview('refresh');
}, "json");
define new style for 'blue' , 'green' and 'red' or whatever you like

Related

Apply CSS class dynamically on TS file

I have inline HTML content on ts file as shown below.
"<div style=\"font-size: 20px;\">" + remainingAmount.toLocaleString() + "</div>"
Now I need to apply color: red according to the condition.
i.e if(this.isSpentOver) color:red else default
I can do this in HTML file like below:
[ngClass]="{'color-red': isSpentOver}"
But how can I do that on ts file?
Update:
.ts
myMethod(){
if (spent > totalBudget) {
this.color = "red";
}
}
showChart(){
"<div style=\"font-size: 20px;color:" + this.color + "\">" +
remainingAmount.toLocaleString() + "</div>"
}
Old
If the HTML is generated in your component.ts you can simply add that to the styling there, but it won't dynamically change.
myInnerHtml = "<div style=\"font-size: 20px;color: " + this.isSpentOver() + "\">" + remainingAmount.toLocaleString() + "</div>"
isSpentOver(): string {
(this.spentData)? return 'red': return 'initial';
}
If you're looking to dynamically style generated html, one of the easier routes is to just use an ElementRef and any time your spentData changes (and the color needs to be updated) call the method that gets the elementRef and changes the color. There are a lot of solid SO questions/answers on Angular, ElementRef, and querySelector() methods so I won't drop how that works here.

Embed specific range from Google Sheets in website so that it is editable by website users

I want to embed a specific range of cells from a Google Docs spreadsheet (or if that doesn't work the whole sheet without header and toolbar) in a website, so that any website visitor can input their data.
I know how to embed a specific range of cells an html table, but that doesn't allow website users to edit the sheet.
A similar question was asked several years ago here but the suggested solution doesn't seem to work anymore.
I called this the htmlSpreadsheet you can use as a dialog or deploy as webapp the doGet is already to go. It's still a pretty simple app. There's a lot of room for customization.
Here's the code.gs file:
function onOpen()
{
SpreadsheetApp.getUi().createMenu('HTML Spreadsheet')
.addItem('Run Spreadsheet in Dialog', 'htmlSpreadsheet')
.addToUi();
}
var SSID='SpreadSheetID';
var sheetName='Sheet1';
function htmlSpreadsheet(mode)
{
var mode=(typeof(mode)!='undefined')?mode:'dialog';
var br='<br />';
var s='';
var hdrRows=1;
var ss=SpreadsheetApp.openById(SSID);
var sht=ss.getSheetByName(sheetName);
var rng=sht.getDataRange();
var rngA=rng.getValues();
s+='<table>';
for(var i=0;i<rngA.length;i++)
{
s+='<tr>';
for(var j=0;j<rngA[i].length;j++)
{
if(i<hdrRows)
{
s+='<th id="cell' + i + j + '">' + '<input id="txt' + i + j + '" type="text" value="' + rngA[i][j] + '" size="10" onChange="updateSS(' + i + ',' + j + ');" />' + '</th>';
}
else
{
s+='<td id="cell' + i + j + '">' + '<input id="txt' + i + j + '" type="text" value="' + rngA[i][j] + '" size="10" onChange="updateSS(' + i + ',' + j + ');" />' + '</th>';
}
}
s+='</tr>';
}
s+='</table>';
//s+='<div id="success"></div>';
s+='</body></html>';
switch (mode)
{
case 'dialog':
var userInterface=HtmlService.createHtmlOutputFromFile('htmlss').setWidth(1000).setHeight(450);
userInterface.append(s);
SpreadsheetApp.getUi().showModelessDialog(userInterface, 'Spreadsheet Data for ' + ss.getName() + ' Sheet: ' + sht.getName());
break;
case 'web':
var userInterface=HtmlService.createHtmlOutputFromFile('htmlss').setWidth(1000).setHeight(450);
return userInterface.append(s).setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
}
function updateSpreadsheet(i,j,value)
{
var ss=SpreadsheetApp.openById(SSID);
var sht=ss.getSheetByName(sheetName);
var rng=sht.getDataRange();
var rngA=rng.getValues();
rngA[i][j]=value;
rng.setValues(rngA);
var data = {'message':'Cell[' + Number(i + 1) + '][' + Number(j + 1) + '] Has been updated', 'ridx': i, 'cidx': j};
return data;
}
function doGet()
{
var output=htmlSpreadsheet('web');
return output;
}
This is the htmlss.html file:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function() {
});
function updateSS(i,j)
{
var str='#txt' + String(i) + String(j);
var value=$(str).val();
$(str).css('background-color','#ffff00');
google.script.run
.withSuccessHandler(successHandler)
.updateSpreadsheet(i,j,value)
}
function successHandler(data)
{
$('#success').text(data.message);
$('#txt' + data.ridx + data.cidx).css('background-color','#ffffff');
}
console.log('My Code');
</script>
<style>
th{text-align:left}
</style>
</head>
<body>
<div id="success"></div>
Following post will be helpfull:
https://support.google.com/docs/answer/37579?hl=fr&ref_topic=2818998
And with some added value, the following is the template you may want to try, where ------ is specific code to your sheet
<iframe style="border: 0;" src="https://docs.google.com/spreadsheets/-----/pubhtml?gid=--------&range=C2:E&chrome=false&single=true&widget=false&headers=false" width="800" height="750" frameborder="0" scrolling="yes"><span data-mce-type="bookmark" style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" class="mce_SELRES_start"></span><span data-mce-type="bookmark" style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" class="mce_SELRES_start"></span><span data-mce-type="bookmark" style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" class="mce_SELRES_start"></span></iframe>

New Line '\n' is not working in Typescript

I am creating a list item in typescript component which will be displayed in the UI. The List items should be displayed in separate lines. So i added new line char \n as below. But still the list items are shown in same line. Below is the code. Any idea why it doesn't work?
Typescript Code:
#Output() excludeDisplay: any = '';
#Output() includeDisplay: any = '';
includeValues: any = '';
excludeValues: any = '';
this.includeValues += this.merId + ',' + this.explodeStatus + '\n';
console.log("include values are "+ this.includeValues);
this.excludeValues += this.merId + ',' + this.explodeStatus + '\n';
console.log("exclude values are "+ this.excludeValues);
this.includeDisplay = this.includeValues;
this.excludeDisplay = this.excludeValues;
Html Code:
<ul id="excludedUl" required>{{ excludeDisplay }}</ul>
<ul id="includedUl" required>{{ includeDisplay }}</ul>
CSS Code:
#includedUl {
float: right;
width: 33%;
}
#excludedUl {
float: right;
width: 33%;
}
Need to use fix width:
<div style="width: 500px;white-space: pre-line">{{property}}</div>
In typescript use '\n' to add new line.
\n does not cause a line break in html.
You'll need to use a <br/> or wrap your text in a block element.
this.includeValues += this.merId + ',' + this.explodeStatus + '<br/>';
this.excludeValues += this.merId + ',' + this.explodeStatus + '<br/>';
Or
this.includeValues += '<div>' + this.merId + ',' + this.explodeStatus + '</div>';
this.excludeValues += '<div>' + this.merId + ',' + this.explodeStatus + '</div>';
If the information is only going to be displayed in the HTML, you can use the CSS property white-space. For breaking just the '\n' character then this should work white-space: pre-line; as mentioned here and for the documentation check MDN.
If you still need the original text with \n included for something else, you can always make a call to the Str.replace method, to change all \n into <br/>, so the template works as expected. You could do something like this:
this.includeDisplay = this.includeValues.replace(/\n/g, '<br />');
You can refer to MDN docs.

Odd,Even in ng-repeat Angular

I want to detect odd or oven in ng-repeat . now i have a fiddle that display some dots show/hide randomly , now i want to change background to not only red , for example odd = green and even = red .
function MyCtrl($scope, $timeout) {
$scope.lights = [0,1,2,3,4,5,6,8,9,10,11,12,13,14,15,16,17,18,19,20];
$scope.currentLight = 0;
function light(index){
if($scope.lights.length < index) {
light(0);
} else {
$scope.currentLight = index;
index = Math.floor((Math.random() * 20) + 1);
$timeout(function(){
light(index);
}, 1000);
}
}
light(0);
}
Any advice ?
you can use ng-class-odd and ng-class-even
from https://docs.angularjs.org/api/ng/directive/ngClassOdd
<ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
<li ng-repeat="name in names">
<span ng-class-odd="'odd'" ng-class-even="'even'">
{{name}}
</span>
</li>
</ol>

no css formatting in jquery listview ajax

I am fairly new to jquery all together. Basically what I have done is made a dynamic gallery populated from images retrieved from an ajax call. The images are appended to a unordered list and supposed to receive special css formatting specific to the image gallery, other ul lists are untouched. Everything works great, however when I view the gallery, the proper css formatting is not rendered on the images. I have searched all over stackoverflow and tried many of the options presented to similar problems including .listview('refresh'); and after an ajax complete: as well as some other solutions. Nothing is working. If I navigate away from the page and come back, the formatting is applied. Here is the following code I am working with.
Link to Gallery
$('ul#fieldList').append('<li id="albums"><img src="images/1.jpg"><h3>'+value.name+'</h3><p>'+value.description+'</p><div class="ui-li-count">'+value.count+' Images</div></li>');
onClick Function
function GetUserPhotos(albumid) {
console.log("Get User Photos Function Ran");
var get_user_photos_album_id = albumid;
var get_user_photos_client_id = window.localStorage.getItem("client_id");
var get_user_photos_user_id = window.localStorage.getItem("user_id");
console.log("Assign Variables from local storage");
var formData = {
user_id: get_user_photos_user_id,
client_id: get_user_photos_client_id,
album_id: get_user_photos_album_id
}; //Array
$.ajax({
url: "client_photos.php",
type: "POST",
data: formData,
async: "false",
success: function (data) {
$("ul#photosList li#photos").remove();
$("#test1").html('');
//data - response from server
var PhotoData = $.parseJSON(data);
console.log("PhotoData json data parsed");
$("ul#fieldList li#albums").remove();
$.each(PhotoData, function (key, value) {
$('ul#photosList').append('<li id="photos"><a rel="' + value.album + '" href="http://www.myphotoshootapp.com/cms/uploads/' + value.client_id + '/' + value.album + '/' + value.id + '.' + value.ext + '" class="swipebox" title="' + value.fullname + '""><img src="http://www.myphotoshootapp.com/cms/uploads/thumbs/' + value.client_id + '/' + value.album + '/' + value.id + '.' + value.ext + '" alt="' + value.fullname + '" /></a></li>');
});
Swipe();
},
complete: function () {
$('#ul#photosList').listview('create');
$.mobile.changePage("#Gallery1");
}
});
}
DIV Item's Are Added To
<div data-role="content">
<ul data-role="listview" data-inset="true" id="photosList">
<li id="title">Photos</li>
<div class="main" id="test1"><img src="images/ajax-loader.gif" alt="Loading..." /></div>
</ul>
</div>
And CSS
li#photos { float: left !important; width: 33.33333333% !important; }
li#photos a { display: block !important; margin: 5px !important; border: 1px solid #3c3c3c !important; }
li#photos img { display: block !important; width: 100% !important; height: auto !important; }
As I said, I am pretty new to this and learning as I go, I have learned so much from reading a lot of other questions here but this one I can not figure out. Thanks for the help.
On the first visit, a bunch of extra classes like ui-btn, ui-btn-icon-right, ui-li-has-arrow, ui-li, ui-li-has-thumb, ui-btn-up-c are being added and the second time, only my normal formatting is applied.
First Visit
This image shows what the css formatting looks like on the first page visit
Here's Image
Second Visit
This image shows what the css formatting looks like when I return to the page (LIKE ITS SUPPOSED TO)
Here's Image

Resources