Javascript filled unsorted list auto scroll - javascript

I'm struggling to make this idea of mine work..
The idea is to auto-scroll the dynamically filled unsorted list.
This is how I've build the Unsorted List with List Items in JavaScript
$.getJSON(sportlink_url + 'programma?gebruiklokaleteamgegevens=NEE&aantaldagen=' + programma_dagen + '&eigenwedstrijden=JA&thuis=JA&uit=JA&' + sportlink_clientID, function (uitslag) {
for (let i = 0; i < Object.keys(uitslag).length; i++) {
//for (let i = 0; i < 1; i++) {
var aanvangstijd = uitslag[i].aanvangstijd;
var thuisteam = uitslag[i].thuisteam;
var uitteam = uitslag[i].uitteam;
var accommodatie = uitslag[i].accommodatie;
var competitiesoort = uitslag[i].competitiesoort;
var datumNumber = uitslag[i].datum.substring(0,2);
var datumMonth = uitslag[i].datum.slice(-4);
var datumMonthClean = datumMonth.substring(0,3);
//Fetch the DIV
var el = document.getElementById("match_program");
//Create new list item
var node = document.createElement("li");
node.setAttribute('role', 'presentation');
//Create ticketDiv
var ticketDiv = document.createElement("div");
ticketDiv.setAttribute('class', 'tg-ticket');
//Create timeBox
var timeBox = document.createElement("time");
timeBox.setAttribute('class', 'tg-matchdate');
timeBox.innerHTML = (datumNumber + " <span>" + datumMonthClean + "</span>");
//Create matchdetail
var matchDetail = document.createElement("div");
matchDetail.setAttribute('class', 'tg-matchdetail');
matchDetail.innerHTML = ("<h4>" + thuisteam + "<span> - </span>" + uitteam + "   |   " + aanvangstijd + ", " + accommodatie);
//Create themeTag
var themeTag = document.createElement("span");
themeTag.setAttribute('class', 'tg-theme-tag');
themeTag.innerHTML = (competitiesoort);
//Build the hole thing
ticketDiv.appendChild(timeBox);
matchDetail.appendChild(themeTag);
ticketDiv.appendChild(matchDetail)
node.appendChild(ticketDiv);
el.appendChild(node);
This is the Unsorted List in HTML
<ul id="match_program" class="tg-tickets tg-tabnav" role="tablist" data-autoscroll="">
</ul>
This is the function i'm currently using for auto-scroll, but it has .ulContent').height() > $('.ulContainer').height() and because my ulContent doesn't have a prefix height in CSS it's not going to work..
And I can't put a height prefix in CSS for the ulContent cause I don't know on forehand if it's going to be 500px of 800px, the unsorted list is being filled from a JSON string.
$(document).ready(function() {
if($('.ulContent').height() > $('.ulContainer').height()) {
setInterval(function () {
start();
}, 3000);
}
});
function animateContent(direction) {
var animationOffset = $('.ulContainer').height() - $('.ulContent').height();
if(direction == 'up') {
animationOffset = 0;
}
}
The animatie function is being called at the bottom of the HTML file just before the closing tags of the body

I manged to figure it out;
var amountGames = Object.keys(uitslag).length
var calulContent = amountGames * 116 + 500;
var setulContent = calulContent + "px";
document.getElementById('ulContent').style.height= setulContent;
That way the ulContent is always filled and the container uses a fixed number of 500px;

Related

Attempting to retrieve a <select>'s .value with jQuery

So I have this HTML Code/Javascript,
var spellNumber = 0;
function createSpell() {
var spellOption = document.createElement("option");
var spellOption2 = document.createElement("option");
var spellSelect = document.createElement("select");
var spellLabel = document.createElement("label");
var spellEnvelope = document.createElement("p");
spellOption.innerHTML = 'Vanish';
spellOption.setAttribute('value', 'vanish');
spellOption2.innerHTML = 'Teleport';
spellOption2.setAttribute('value', 'teleport');
spellSelect.setAttribute('id', 'spell');
spellSelect.setAttribute('name', 'spell');
spellLabel.setAttribute('for', 'spell');
spellLabel.innerHTML = '<strong>Spell ' + (spellNumber + 1) + '</strong> = ';
spellEnvelope.appendChild(spellLabel);
spellEnvelope.appendChild(spellSelect);
spellSelect.appendChild(spellOption);
spellSelect.appendChild(spellOption2);
document.getElementById("spells").appendChild(spellEnvelope);
spellNumber += 1;
}
createSpell()
function generateYaml() {
var spellCheck = 1;
for (allSpells = 0; allSpells < spellNumber; allSpells++) {
var multipleSpell = $("#spell:contains('Spell " + spellCheck + "')").val();
console.log(multipleSpell);
spellCheck++
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="spells"></div>
<button onClick="createSpell()">Add A Spell</button>
<button id="button" onClick="generateYaml()">Make the Magic Happen</button>
And am trying to retrieve the .value of the <select id="spell"> options. However, the console returns an undefined, instead of vanish or teleport.
Can anyone point me in the right direction for this?
Well:
Id should be unique so I added spellSelect.setAttribute('id', 'spell' + spellNumber); ( + other rows)
Also multipleSpell = $("#spell" + spellCheck).val();
And console.log(multipleSpell); is called only once at the begining -> you should change it to function too
`
var spellNumber = 0;
function createSpell() {
var spellOption = document.createElement("option");
var spellOption2 = document.createElement("option");
var spellSelect = document.createElement("select");
var spellLabel = document.createElement("label");
var spellEnvelope = document.createElement("p");
spellOption.innerHTML = 'Vanish';
spellOption.setAttribute('value', 'vanish');
spellOption2.innerHTML = 'Teleport';
spellOption2.setAttribute('value', 'teleport');
spellSelect.setAttribute('id', 'spell' + spellNumber);
spellSelect.setAttribute('name', 'spell' + spellNumber);
spellLabel.setAttribute('for', 'spell' + spellNumber);
spellLabel.innerHTML = '<strong>Spell ' + (spellNumber + 1) + '</strong> = ';
spellEnvelope.appendChild(spellLabel);
spellEnvelope.appendChild(spellSelect);
spellSelect.appendChild(spellOption);
spellSelect.appendChild(spellOption2);
document.getElementById("spells").appendChild(spellEnvelope);
spellNumber += 1;
}
createSpell()
function generateYaml() {
var spellCheck = 0;
for (allSpells = 0; allSpells < spellNumber; allSpells++) {
var multipleSpell = $("#spell" + spellCheck).val();
console.log(multipleSpell);
spellCheck++
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="spells"></div>
<button onClick="createSpell()">Add A Spell</button>
<button id="button" onClick="generateYaml()">Make the Magic Happen</button>
var multipleSpell = $("#spell:contains('Spell " + spellCheck + "')").val();
More info here.
Edited:
Well, i see you are trying to get all select values. Why not try this?
function generateYaml() {
var spellCheck = 1;
var selects = $("select").each(function (index, element) {
var value = $(element).val()
console.log("The value at index %d is %s", index, value);
spellCheck++
});
}
This way you iterate over all the selects, and get their values inside the loop. Try it here (open the developer console):https://darkcyanpointlessbooleanvalue--parzibyte.repl.co/

Get the text from textarea line by line?

HTML Code
<textarea id="test"></textarea>
<button id="button_test">Ok</button>
Javascript
$(document).ready(function()
{
$("#test").val("123e2oierhqwpoiefdhqwopidfhjcospid");
});
$("#button_test").on("click",function()
{
var as=document.getElementById("test").value;
console.log(as);
});
We can get the values from textarea line by line using val and split functions. But
Is it possible to get the value from textarea line by line for very long word?.In the example i need to get the output as 123e2oierhqwpoiefdhqwo and pidfhjcospid as separate values.
Jsfiddle link here
You can use something like this. This will insert line breaks into into the textarea.
Credits: https://stackoverflow.com/a/4722395/4645728
$(document).ready(function() {
$("#test").val("123e2oierhqwpoiefdhqwopidfhjcospid");
});
$("#button_test").on("click", function() {
ApplyLineBreaks("test");
var as = document.getElementById("test").value;
console.log(as);
});
//https://stackoverflow.com/a/4722395/4645728
function ApplyLineBreaks(strTextAreaId) {
var oTextarea = document.getElementById(strTextAreaId);
if (oTextarea.wrap) {
oTextarea.setAttribute("wrap", "off");
} else {
oTextarea.setAttribute("wrap", "off");
var newArea = oTextarea.cloneNode(true);
newArea.value = oTextarea.value;
oTextarea.parentNode.replaceChild(newArea, oTextarea);
oTextarea = newArea;
}
var strRawValue = oTextarea.value;
oTextarea.value = "";
var nEmptyWidth = oTextarea.scrollWidth;
var nLastWrappingIndex = -1;
for (var i = 0; i < strRawValue.length; i++) {
var curChar = strRawValue.charAt(i);
if (curChar == ' ' || curChar == '-' || curChar == '+')
nLastWrappingIndex = i;
oTextarea.value += curChar;
if (oTextarea.scrollWidth > nEmptyWidth) {
var buffer = "";
if (nLastWrappingIndex >= 0) {
for (var j = nLastWrappingIndex + 1; j < i; j++)
buffer += strRawValue.charAt(j);
nLastWrappingIndex = -1;
}
buffer += curChar;
oTextarea.value = oTextarea.value.substr(0, oTextarea.value.length - buffer.length);
oTextarea.value += "\n" + buffer;
}
}
oTextarea.setAttribute("wrap", "");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<textarea id="test"></textarea>
<button id="button_test">Ok</button>
Use .match(/pattern/g). As your OP ,pattern should start \w (Find a word character) and match string sequence {start,end}
$("#button_test").on("click",function()
{
var as=document.getElementById("test").value;
console.log(as.match(/(\w{1,22})/g));
});
If you made the textarea width fixed using css you could do this:
css
textarea { resize: vertical; }
javascript
$("#button_test").on("click",function(){
var as=document.getElementById("test").value;
var len = document.getElementById("test").cols;
var chunks = [];
for (var i = 0, charsLength = as.length; i < charsLength; i += len) {
chunks.push(as.substring(i, i + len));
}
console.log(chunks);
});
This is probly not the best way, but it works and i hope it could help you.
First thing, i found the textarea allow 8px for default fontsize charactere.
Exemple :
Textarea with 80px
=> Allow line with 10 char maximum, all other are overflow on new line.
From this you can do a simple function like this :
$("#button_test").on("click",function()
{
console.clear();
var length_area = $("#test").width();
var length_value = $("#test").val().length;
var index = Math.trunc(length_area/8);
var finalstr = $("#test").val().substring(0, index) + " " + $("#test").val().substring(index);
console.log(finalstr);
});
Here the JSFiddle
The <textarea> element has built in functionality to control where words wrap. The cols attribute can be set (either harded coded in the HTML or set with the .attr() method using jQuery). The attribute extends the text area horizontally and it also automatically wraps text at the set value.
Example jsFiddle
$("#test").val("123e2oierhqwpoiefdhqwopidfhjcospid");
var newString = $("#test").val().toString();
var splitString = parseInt($("#test").attr("cols"), 10) + 1;
var stringArray = [];
stringArray.push(newString);
var lineOne = stringArray[0].slice(0, splitString);
var lineTwo = stringArray[0].slice(splitString);
var lineBreakString = lineOne + "\n" + lineTwo;
console.log(lineTwo);
$('#test').after("<pre>" + lineBreakString + "</pre>");
$("#test").val("123e2oierhqwpoiefdhqwopidfhjcospid");
var newString = $("#test").val().toString();
var splitString = parseInt($("#test").attr("cols"), 10) + 1;
var stringArray = [];
stringArray.push(newString);
var lineOne = stringArray[0].slice(0, splitString);
var lineTwo = stringArray[0].slice(splitString);
var lineBreakString = lineOne + "\n" + lineTwo;
$('#test').after("<pre>" + lineBreakString + "</pre>");
//console.log(lineBreakString);
pre {
color: green;
background: #CCC;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<textarea id="test" cols='21'></textarea>
<button id="button_test">Ok</button>
The example addresses the specific question asked. If you want to deal with larger blocks of text, you should use the .each() method and for loops to iterate over each line break.
Documentation:
.slice()
textarea
.push()
.parseInt()
.attr()

Create inner divs within a loop

Can someone explain to me how I do appending divs currently it just concats everything and it all looks like a mess. I want each trip to be inside separate divs
var origin = ' ';
var destination = ' ';
var distance = ' ';
var oneConcatedTrip = ' ';
var outerDiv = document.getElementById('demo');
var innerDiv = document.createElement('div');
var i = 1;
var query = firebase.database().ref('users/' + uid +'/waypoints/Work/2016/06').orderByKey();
query.once("value")
.then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var key = childSnapshot.key;
var childData = childSnapshot.val();
origin = childSnapshot.val().origin;
destination = childSnapshot.val().destination;
distance = childSnapshot.val().distance;
innerDiv.className = 'block-' + i++;
outerDiv.appendChild(innerDiv);
oneConcatedTrip = origin + ' ' + destination + ' ' + distance;
innerDiv.innerHTML += oneConcatedTrip;
});
outerDiv.textContent = innerDiv.innerHTML;
});
You are reusing the same reference of innerDiv. You need to create different new div for every trip.
Move : var innerDiv = document.createElement('div'); into the for loop.
Check example below :
Your code :
Note the innerDiv has a blue border and its only one box that you can see.
var outerDiv = document.getElementById('demo');
var innerDiv = document.createElement('div');
for (var i = 1; i < 5; i++) {
innerDiv.className = 'block';
outerDiv.appendChild(innerDiv);
var oneConcatedTrip = 'origin destination distance';
innerDiv.innerHTML += oneConcatedTrip;
}
.block {
border: 2px blue solid;
}
<div id="demo">
</div>
Correct Way
Now that for every iteration there is a new div, note that there are different boxes and not just one.
var outerDiv = document.getElementById('demo');
for (var i = 1; i < 5; i++) {
var innerDiv = document.createElement('div');
innerDiv.className = 'block';
outerDiv.appendChild(innerDiv);
var oneConcatedTrip = 'origin destination distance';
innerDiv.innerHTML += oneConcatedTrip;
}
.block {
border: 2px blue solid;
}
<div id="demo">
</div>

Add html code to a dynamically generated div

I have a js question that annoys me for the last couple of days.
i have a parallax template, where the parallax elements are generated automatically from js file.So i can add css style like transitions etc., but i would like to add some links on top of the divs, or some kind of on clik events.
What i think i have to look so far is in this fille (where the id of the divs are created):
enter //Parallax Element 2
var item = {};
item.name = "#tree21";
item.stackOrder = 1;
item.content = "image";
item.image = "images/parallax/bg2.png";
item.sizes = {w:"350",h:"350"};
item.screenPos = ["40%","-100%","300%","-115%"];
item.visibility = ["true","true","true","true"];
item.parallaxScene = true;
item.bPos = 200;
item.mouseSpeed = 15;
items.push(item);
and here (where i think the divs are generated
createScenes: function () {
//Resize Parallax Elements if responsive
if (responsive) {
var screenProp = this.maxWidth / 1920;
} else {
var screenProp = 1;
}
for (var i = 0; i < items.length; i++) {
if (jQuery(items[i].name).length == 0) {
jQuery("#parallax-container").append("<div id='" + items[i].name.substring(1, (items[i].name.length)) + "' class='parallaxItem'></div>");
}
Thank you!
Store a reference to your new div:
var div = jQuery("<div id='"
+ items[i].name.substring(1, (items[i].name.length))
+ "' class='parallaxItem'></div>")
.appendTo(jQuery("#parallax-container"));
jQuery(div).append('...');

Titanium Horizontal layout inside tablerow

I want in a tablerow to have a label with a day's name. this mean that i dont know the actual width of the label, and that label.toImage().width does not return the actual size even after postlayout event. And also i want to have horizontally aligned a scrollview with a random text, sometimes very big. What i have is:
var storehoursscrollingmessagestyle = {
left:"10dp",
font:{fontSize:'18dp',fontWeight:"bold"}
};
var storehoursscrollviewstyle = {
contentWidth: 'auto',
contentHeight: 'auto',
height: '70dp',
width:Ti.UI.FILL,
scrollType: 'horizontal'
};
var storehoursrowstylegray={
classNane:"storeoptions",
selectedBackgroundColor:"#E8E8E8",
backgroundColor:"#E8E8E8",
height:"70dp"};
var storehoursrowlabelstyle={
left:"10dp",
height:"70dp",
font:{fontSize:'18dp',fontWeight:"bold"},
color:"Black"
};
var storehoursviewrowstyle ={
width:'200dp',
height:'70dp',
layout:'horizontal'
};
var storehoursbuttontitleview = Titanium.UI.createLabel(storehoursrowlabelstyle);
storehoursbuttontitleview.text = dayMappings[today] + " " + openTimeFormatted + " - " + closeTimeFormatted;
storehoursbuttonview.add(storehoursbuttontitleview);
var view = Ti.UI.createView(storehoursviewrowstyle);
var scrollview = Ti.UI.createScrollView(storehoursscrollviewstyle);
scrollview.add(storehoursscrollingmessagetitleview);
view.add(storehoursbuttontitleview);
var subviewviewforscrollview = Ti.UI.createView(storehoursviewrowstyle);
subviewviewforscrollview.add(scrollview);
view.add(subviewviewforscrollview);
storehoursbuttonview.add(view);
if i set width:'30%' to storehoursscrollviewstyle the horizontal layout will be shown as it should but if i set 100% the scrolling view disappears.
So my question is how to have a label and a scrollingview inside a table row, without knowing their sizes and without setting a hardcoded width value for each other.
I did it by adding postlayout event to my label, also removed horizontal layout from view and hardcoded widths.
function storehoursbuttontitleview_postlayout(e) {
if (e.source.set == null) {
var storehoursscrollingmessagetitleview = Titanium.UI.createLabel(storehoursscrollingmessagestyle);
storehoursscrollingmessagetitleview.text = e.source.closedMessage;
var view = Ti.UI.createView(storehoursviewrowstyle);
view.left = e.source.size.width + 20 + "dp";
var scrollview = Ti.UI.createScrollView(storehoursscrollviewstyle);
view.add(scrollview);
if (Titanium.Platform.name != 'android') {
var str = e.source.closedMessage;
var chunks = [];
for (var i = 0, charsLength = str.length; i < charsLength; i += 100) {
chunks.push(str.substring(i, i + 100));
}
var finalwidth = 0;
for (i=0; i<chunks.length; i++) {
var storehoursscrollingmessagetitleviewtemp = Titanium.UI.createLabel(storehoursscrollingmessagestyle);
storehoursscrollingmessagetitleviewtemp.text = chunks[i];
finalwidth = finalwidth + storehoursscrollingmessagetitleviewtemp.toImage().width;
}
var labelInsideScrollWidth = finalwidth;
storehoursscrollingmessagetitleview.width = finalwidth + 10 + "dp";
scrollview.add(storehoursscrollingmessagetitleview);
}
else {
scrollview.add(storehoursscrollingmessagetitleview);
}
e.source.row.add(view);
e.source.set = true;
}
}

Categories