wrap spans around individual letters of a div using JQuery - javascript

I'm trying to insert span elements around every letter of a div's text, belonging to a given class, using JQuery.
But my code only returns words, not letters. What is wrong?
$(function() {
var title = $(".js-split-text").text();
var titleText = title.split(" ");
var newTitle = [];
var letterCount = 0;
titleText.forEach(function(el) {
var titleElement = "<span>" + el + "</span>";
newTitle.push(titleElement);
letterCount++;
if (titleText.length === letterCount) {
var newTitleText = newTitle.join(" ");
$(".js-split-text")
.html(newTitleText)
.css({ opacity: 1 });
var aniTime = 0;
var offset = 500;
$(".js-split-text span").each(function() {
var currentSpan = $(this);
aniTime += offset;
setTimeout(function() {
currentSpan.addClass("animate");
}, aniTime);
});
}
});
});

You're are wrapping the spans around the words in the text with this code
var titleElement = "<span>" + el + "</span>";
If you want to wrap the spans around the letters, you should further split the words into letters like so
var titleElement = "<span>" + el.split('').join("</span><span>") + "</span>";

Related

How to return to the starting position in a dynamically rebuilt table after having followed a link from it?

I rebuild a table (tbody) from the local storage. When it is necessary, I rebuild the <a> tag to get a link to an image. Contrary to what happen normally, when returning from the linked document or image to the calling document containing the rebuilt table, the cursor position nor the scrollbar position is retained, and the table is re-positioned at the beginning (row 0, col 0). I would like that the user would not have to scroll again to find it starting position (with the link) in the table.
The problem is simple to explain and I already did it. By clicking to expand a small view of a table in order to get a full view of it on a new page, I have to dynamically rebuild this table from information in the localstorage: firstly call the function storeLocOeuvresTbl() in the origin page; secondly, the function getInventOeuvresTblFromStoreLoc() in the destination page. This can be done by clicking on the link according to the code here : Le contenu de cette table peut être trié en cliquant sur les entêtes de colonnes.
Veuillez suivre ce lien
Expand
pour agrandir la table sur une page séparée..
If I follow a link from a cell in the built table in the destination page and return to this page from any other document/page accessed through this link, the cursor and scrollbar positions are lost. I suppose having to specify some property/attribute.
Which property/attribute do I have to specify for a dynamically built table so that the table from which I followed the link, does not move to the initial pos (0,0) when I return from this link. If I have to specify a property to keep the position, at which level? Div, table contained in the div, tbody?
Whit a dynamically built table, the normal behavior is perturbed.
Here is a link to a test page simplifying this problem:
http://www.danielpisters.be/testTable.html
Click bellow the table and you get a full view of the table in
http://www.danielpisters.be/testExpandTestTable.html
Move right to the column header "tLink" (all the others are "Foo", "Bar"). Then move down in the column until you reach a cell with a link. Click on it and you will see an image on another page. Returning from it, the position on the cell containing the link is lost, becoming 0,0.
// Build the table from the origin document
<script type="text/javascript">
function storeLocOeuvresTbl()
{
var oTable = document.getElementById('myOeuvresTable');
var s = "";
var stopAlert = true;
if (oTable == null) // TJC: Invalid ID, ignore it
{
alert("myOeuvresTable not found!");
return "";
}
var versIE = isIE();
var aTBODY = oTable.getElementsByTagName("tbody");
localStorage.setItem("myOeuvresTableTBlen", aTBODY.length);
// set the CSS class for each one of the TR tags
for (var i = 0; i < aTBODY.length; i++)
{
// get an array of all the TR tags in the TBODY
// TJC: It's actually a NodeList, but you can largely
// treat it as an array
var aTR = aTBODY[i].getElementsByTagName("tr");
localStorage.setItem("myOeuvresTableTB" + i + "len", aTR.length);
for (var j = 0; j < aTR.length; j++)
{
var aTD = aTR[j].getElementsByTagName("td");
localStorage.setItem("myOeuvresTableTB" + i + "TR" + j + "len", aTD.length);
var aTDlen = parseInt(localStorage.getItem("myOeuvresTableTB" + i + "TR" + j + "len"));
for (var k = 0; k < aTD.length; k++)
{
s = s + aTD[k].id + ": " + aTD[k].innerHTML + "|";
var tdId = "myOeuvresTableTB" + i + "TR" + j + "TD" + k;
var innerHTML = "";
if (aTD[k].innerHTML.length > 0)
{
innerHTML = aTD[k].innerHTML;
}
else
{
innerHTML = " ";
}
localStorage.setItem(tdId, innerHTML);
innerHTML = localStorage.getItem(tdId);
if (stopAlert == false && (versIE != false) && (versIE < 9))
{
alert("innerHTML get: " + innerHTML);
if (window.confirm("Stop Alert?"))
{
stopAlert = true;
}
}
}
s = s + "\n";
}
}
return s;
}
// Rebuild onLoad of the destination document
<script type="text/javascript">
function getInventOeuvresTblFromStoreLoc()
{
var tbl = document.getElementById('myOeuvresTable');
var s = "";
var tdId = "";
var innerHTML = "";
var aTBODYlen = 0;
var aTRlen = 0;
var aTDlen = 0;
var stopAlert = true;
var arrEvent = new Array("onMouseOver", "onMouseOut", "onClick", "onDbleClick", "onMouseUp", "onMouseDown", "onFocus", "onBlur");
var DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/;
if (tbl == null) // TJC: Invalid ID, ignore it
{
alert("myOeuvresTable not found!");
return "";
}
var versIE = isIE();
aTBODYlen = parseInt(localStorage.getItem("myOeuvresTableTBlen"));
// set the CSS class for each one of the TR tags
for (var i = 0; i < aTBODYlen; i++)
{
// get an array of all the TR tags in the TBODY
// TJC: It's actually a NodeList, but you can largely
// treat it as an array
var tblBody = tbl.tBodies.item(i);
aTRlen = parseInt(localStorage.getItem("myOeuvresTableTB" + i + "len"));
for (var j = 0; j < aTRlen; j++)
{
var row = document.createElement("tr");
aTDlen = parseInt(localStorage.getItem("myOeuvresTableTB" + i + "TR" + j + "len"));
for (var k = 0; k < aTDlen; k++)
{
var cell = document.createElement("td");
tdId = "myOeuvresTableTB" + i + "TR" + j + "TD" + k;
innerHTML = localStorage.getItem(tdId);
if (innerHTML.substr(0, 7).toLowerCase() == "<a href")
{
var link = document.createElement("a");
var indDblQuote1 = innerHTML.indexOf('"');
var indDblQuote2 = innerHTML.indexOf('"', indDblQuote1 + 1);
var indOf1 = innerHTML.indexOf(">");
var indOf2 = innerHTML.toLowerCase().indexOf("</a>");
var cellLink = innerHTML.substring(indDblQuote1 + 1, indDblQuote2);
var cellText = innerHTML.substring(indOf1 + 1, indOf2);
if (stopAlert == false && (versIE != false) && (versIE < 9))
{
var s = "innetHTML: " + innerHTML + "; " + "cellLink: " + cellLink + "; " + "cellText: " + cellText;
alert(s);
if (window.confirm("Stop Alert?"))
{
stopAlert = true;
}
}
link.setAttribute('href', cellLink);
link.appendChild(document.createTextNode(cellText));
cell.appendChild(link);
}
else
{
var cellText = document.createTextNode(innerHTML);
cell.appendChild(cellText);
}
row.appendChild(cell);
s = s + tdId + ": " + innerHTML + "|";
}
tblBody.appendChild(row);
s = s + "\n";
}
tbl.appendChild(tblBody);
}
return s;
}
</script>

localstorage multiple values

Alright, so i have textbox where I enter grades, and then they're saved in localstorage and i can see them under my textbox. But if I want to add more text boxes in which i can add more grades, and they will be saved in localstorage but they will be in another array or something how i can do that? I will be grateful for any help.
$(document).ready(function () {
var i = 0;
for (i = 0; i < localStorage.length; i++) {
var gradeID = "grade-" + i;
$('#gradeList').append("<b id='" + gradeID + "'>" + localStorage.getItem(gradeID) + "</b>, ");
}
$('#clear').click(function () {
localStorage.clear();
});
$('#gradeEntryForm').submit(function () {
if ($('#gradeInput').val() !== "") {
var gradeID = "grade-" + i;
var gradeMessage = $('#gradeInput').val();
localStorage.setItem(gradeID, gradeMessage);
$('#gradeList').append("<b class='task' id='" + gradeID + "'>" + gradeMessage + "</b>, ");
var grade = $('#' + gradeID);
task.slideDown();
$('#gradeInput').val("");
i++;
}
return false;
});
$('#gradeList').on("click", "b", function (event) {
self = $(this);
gradeID = self.attr('id');
localStorage.removeItem(gradeID);
self.remove();
});
});
DEMO
You can set dynamic id to your LocalStorage keys which you can relate to your generated TextBoxes
Something like below
localStorage['grade_' + some_id] = value;
You could use the following example:
document.getElementById("addGrade").onclick = function() {
var gradeCell = document.getElementById("gradeCell");
var input = document.createElement("input");
input.type = "number";
var br = document.createElement("br");
gradeCell.appendChild(input);
gradeCell.appendChild(br);
}
EXAMPLE

Get the image filename by first characters using javascript

I have a folder with images that have long filenames, but they all have unique product ID numbers at the beginning
e.g. 1023-Very-Long-Image-Name.jpg.
What I'm trying to do is to get full image filename into my javascript, by just using this unique ID number.
e.g. I need to find an image with ID 1023, which is this one - 1023-Very-Long-Image-Name.jpg
All unique IDs stored in JSON database. So below is an example of my code:
$('.choose-range-cta').click(function () {
var rowID = $(this).attr("id");
var stylesTable = JSON.parse(stylesDB);
var styleHTML = "";
for (var i = 0; i < stylesTable.length; i++) {
if (stylesTable[i].collectionID == rowID) {
var blockTitle = stylesTable[i].styleName;
var blockPrice = stylesTable[i].fromPrice;
var blockSize = stylesTable[i].size;
var blockImageID = stylesTable[i].frontImageID;
styleHTML += "<div class=\"col-lg-4 style-block\"><span class=\"style-name\">" + blockTitle + "</span><span class=\"from-price\">from £" + blockPrice + "</span><span class=\"cta\">Select</span><div class=\"img-box\"><img src=\"" + ImagePath + blockImageID +"\"></div><span class=\"copy\">" + blockSize + "</span></div>";
}
}
$('#style-list').html(styleHTML);
});
Assuming your list is an array, use filter:
var imageArray = [
'1021-Don-Long-Image-Name.jpg',
'1022-Very-Long-Image-Name.jpg',
'1023-Dan-Long-Image-Name.jpg',
'1024-BobLong-Image-Name.jpg'
];
function getName(data, id) {
return data.filter(function (el) {
return el.substring(0, 4) === id;
})[0];
}
var name = getName(imageArray, '1023'); // 1023-Dan-Long-Image-Name.jpg
DEMO

Get full ID searching with a selector

I have a schedule made in a table. Each td has an id that start with "schedule" + dayofweek;
I mark when the schedule starts adding a class ".schedule_start".
I'm searching with a selector and i want to get the full id of the td's with the class "schedule_start"
here is my example:
for (i = 0; i < 7; i++) {
var tag1 = 'schedule-' + i + '-';
if($("td[id ^='" + tag1 + "']").hasClass("schedule_start"))
{
console.log(tag1);
// here i want to return the full id
}
}
You can instead do this:
$('td[id^=schedule].schedule_start').each(function() {
console.log(this.id);
});
try this:
for (i = 0; i < 7; i++) {
var tag1 = 'schedule-' + i + '-';
var $tag = $("td[id ^='" + tag1 + "']");
if($tag.hasClass("schedule_start"))
{
console.log($tag.attr("id");
// here i want to return the full id
}
}

Create list html from selected text in Textarea

I have found various examples of using jquery to wrap selected text from a textarea in html tags, but I would like to adapt this slightly to create a list when multiple lines of text are selected.
Currently the code below wraps the whole selection in the list tags but I would also like to replace all the carriage returns with the closing and opening tags for list items - so each line in the text area is a new list item.
I think one of the problems might be that the .val function reads the text area as a single line.
jquery:
function listText(elementID, openTag, closeTag) {
var textArea = $('#' + elementID);
var len = textArea.val().length;
var start = textArea[0].selectionStart;
var end = textArea[0].selectionEnd;
var selectedText = textArea.val().substring(start, end);
var replacement = openTag + selectedText + closeTag;
textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len));
}
$(document).ready(function () {
$("#BoldIt").click( function() {
listText("markItUp", "<ul><li>", "</li></ul>");
});
});
body:
<textarea id="markItUp" cols="80" rows="20"></textarea>
<br />
<input type="button" value="Bold" id="BoldIt" />
split your text like this:
function listText(elementID, openTag, closeTag) {
var textArea = $('#' + elementID);
var s = "\n";
var len = textArea.val().length;
var start = textArea[0].selectionStart;
var end = textArea[0].selectionEnd;
var selectedText = textArea.val().substring(start, end);
var replacement = "";
var rows = selectedText.substring(start, end).split(s);
for(var i = 0; i < rows.length; i++) {
replacement += openTag + rows[i] + closeTag + s;
}
textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len));
}
$(document).ready(function () {
$("#BoldIt").click( function() {
listText("markItUp", "<ul><li>", "</li></ul>");
});
});

Categories

Resources