string for image won't print correctly - javascript

Ok I have an array myIconPath[] of images "img/myIcons/imgIcon_12.png" <-- one example
I have some javascript that writes that writes a list item for each icon in the array
document.write('<li><a href="' + "test2.jsp" +
'" title="' + myTitleName +
'"><img src="' + myIconPath[i] +
'" alt="' + myAltName + '" /></a></li>');
This works beautifully.
But I want to get rid of the img/myIcons extension so that I can just load "imgIcon_1.png"
When I try that very thing, replacing
<img src="' + myIconPath + '"...
with
<img src="' + 'img/myIcons/' + actImageArray[i] + '"...
it only loads the first icon. the rest are blank. I'm sure there's so syntactical mistake in here. What could it possibly be though?

Use String#replace to replace the path with a blank string and then trim it.
var imgSrc = myIconPath[i].replace('img/myIcons/', '').trim();
document.write('<li><a href="' + "test2.jsp" +
'" title="' + myTitleName +
'"><img src="' + imgSrc +
'" alt="' + myAltName + '" /></a></li>');

Related

How to handle attribute with # in its name

I am facing to problem with Elasticsearch result which is using # in attribute name. Snippet of json result:
{"_index":"logs-2015.12.31","_type":"log","_id":"AVH4eA4QKV0mbJuiIHO1","_score":null,"_source":{"#timestamp":"2015-12-31T14:36:35.378Z","beat":{"hostname":"
I need to interpret its value into jquery code. See the code snippet:
case item._index.startsWith('logs-'):
$('#results-list').append( '<a href="details.jsp?id=' + item._id + '" target="_blank" class="list-group-item">'
+ '<span class="label label-info">' + item._type + '</span>'
+ '<h4 class="list-group-item-heading">' + item._source.source + '</h4>'
+ '<p class="list-group-item-text">' + item._source.#timestamp + ' - ' + item._source.beat.name + '</p>'
+ '<p class="list-group-item-text">' + item._source.message + '</p>'
+ '</a>'
How to handle the attribute if I cannot change the source?
The # character cannot be used in a literal property name, hence you need to use array notation to access it:
item._source['#timestamp']

Retrieve Flickr photo title AND description using jQuery

Annoyingly, the FlickrAPI provides the title and description of a photo in two separate methods. I'm having trouble getting the description of an image from Flickr and was wondering if you could highlight the error in my script.
for (var i = 0; i < photos.photo.length; i++) {
var descPhoto = "https://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key="+API_KEY+"&photo_id="+photos.photo[i].id+"&format=json&nojsoncallback=1";
var descArr = [];
$.getJSON(descPhoto, function(data) {
var value = data.photo.description._content;
descArr.push(value);
});
link = 'https://farm' + photos.photo[i].farm + '.static.flickr.com/' + photos.photo[i].server + '/' + photos.photo[i].id + '_' + photos.photo[i].secret + '_';
title = this._htmlEscape( photos.photo[i].title );
var lightbox = "lightbox";
listItems +=
'<li ' + 'class="' + liClassNoDots + '">' +
'<a href="' + link + self.options.imageSize + '.jpg" title="' + title + '" class="' + aClassNoDots + '" target="_blank" data-lightbox="' + lightbox + '">' +
<img alt="' + title + '" src="' + link + self.options.thumbnailSize +'.jpg"/>' +
'<div class="hover-box">' +
'<p>' + descArr[i] + '</p>' +
'<button class="box-button view">View larger</button>' +
'<button class="box-button request">Request</button>' +
'</div>';
'</a>' +
'</li>';
}
Getting the title is fine and I've checked by API string calls and they work in the address bar of my browser.
I've used console.log() and the array is printed out correctly and I'm getting the descriptions. However, in each <p> tag the script is returning undefined in each instance.
However, if I run the script through the debugger the parapgraph tags are populated with the descriptions. Can somebody help?!
i think the problem is in following code::
..
$.getJSON(description, function(desc) {
value = desc.photo[ i ].description._content;
});
the service url returns photo object whereas you are using photo array, change to:
..
$.getJSON(description, function(desc) {
value = desc.photo.description._content;
console.log( value );
});

RegExp replace innerHTML except if anchor tag or in code tags

my replace function looks like this
post.innerHTML = post.innerHTML.replace(treg,function(m){
return '<span class="tech-word" title="' + _text[m] + '">' + m + '</span>';
}).replace(wreg,function(m){
return '<a class="post-word-link" href="' + _links[m] + '">' + m + '</a>';
}).replace(ireg,function(m){
return '<span id="image_'+m+'"><span class="post-hover-img">' + m + '</span><img src="' + _image[m] + '" class="auto-img"></span>';
});
the regex looks like this
wregex=["word1","word2","word3"];
wreg = RegExp('\\b(' + wregex.join('|') + ')\\b(?=\\W)', 'gi');
When I do this it works great for words, but it also changes anchor tags as well as code blocks. Anyway to stay away from them by updating the regex or is there something else I am missing.

Specific HTML code generator using Jquery

I made a website, but now I came with an idea to make a code generator. You have to insert text in text boxes and it will generate code.
$("input").keyup(function() {
$("#result").text(
'<div width="' + $("#width").val() +
'px" height="' + $("#height").val() +
'px">' + $("#content").val() +
'</div>');
});
I found this solution on http://jsfiddle.net/NzFeb/ but it doesn't work somehow with my code.
You can see what I did (CSS and Markup) at http://go.filiparag.com/mnmuis-generator but now I need Jquery code.
What I have done with Jquery (it doesn't work):
$("input").keyup(function() {
$("#code").text(
'<!--POST-->
<div id="post"> <div id="' + $("#tag").val() + '" class="tag_post"></div>
<a href="' + $("#image-link").val() + '" data-lightbox="' + $("#title").val() + '" title="' + $("#title").val() + '">
<img src="' + $("#image-link").val() + '" width="'IMAGE_WIDTH'" height="'IMAGE_HEIGHT'" id="post-image-right"/> </a>
<text id="post-title">' + $("#title").val() + '</text> <br>
<text id="post-short-story">' + $("#short-story").val() + '</text> <br> <br>
<text id="post-text">
' + $("#story").val() + '
</text>
</div>
<!--POST END-->'
);
});
These id's are from <input type="text"> and <textarea>.
If i understand your problem correctly, this is the desired code or result http://jsfiddle.net/NzFeb/
if so then your problem is here
' width="'IMAGE_WIDTH'" height="'IMAGE_HEIGHT'"'
// is IMAGE_WIDTH a variable or part of the string
// if its a variable use the plus sign
' width="' + IMAGE_WIDTH + '" height="' + IMAGE_HEIGHT + '"'
// if its part of the string remove the single qoute
' width="IMAGE_WIDTH" height="IMAGE_HEIGHT"'
if the fiddle i pointed to is not the desired code then, change text() to html()
$("#code").html(
side note: <text> is not a valid html tag

Creating dynamic html with json taking too much time

I am working on preparing some dynamic html with jquery and json object. but the problem is that when my json object has around 1500 rows it takes ages to load.
is there a way to load the thing faster.
Some code.
$(jQuery.each(jsonObject.AvailableColumns, function (i, l) {
if (type == "manual") {
innerList1 += '<li newText="" valueFormat="' + l.ValueFormat + '" scaleID="' + l.ScaleID + '" scaleType="' + l.ScaleType + '" hasWeights="' + l.HasWeights + '" customColumnType="' + l.CustomColumnType + '" class="" id="li_' + controlId + '"><span id="span_' + controlId + '" title = "' + l.QuestionText + '">' + getDisplayString(l.QuestionText) + '</span><a class="actionLeft"></a></li>';
}
else if (type = "exportall") {
innerList2 += CreateLiWithSpans('li_' + controlId, l.QuestionText, true, false, l.ScaleID, l.ScaleType, l.HasWeights, l.CustomColumnType, l.ValueFormat);
}
controlId++;
}));
$("#itemList").html(innerlist1);
EDIT : createliwithspan method
function CreateLiWithSpans(id, html, isLeft, isAddAll, scaleID, scaleType, hasWeights, customColumnType, valueFormat, newText) {
var ancClass = isLeft ? 'actionRight' : 'actionLeft';
var liObject = "";
if (newText == null) {
newText = "";
}
if (isLeft) {
liObject = '<li newtext="' + newText + '" valueFormat="' + valueFormat + '" scaleID="' + scaleID + '" scaleType="' + scaleType + '" hasWeights="' + hasWeights + '" customColumnType="' + customColumnType + '" class="" id="' + id + '"><span id="span_' + id + '" title = "' + html + '">' + getDisplayString(html) + '</span><span style="margin:0 10px 0 20px;pagging:0"><input title = "' + (newText == "" ? html : newText) + '" type="text" id="' + id + 'displayText" value="' + (newText == "" ? html : newText) + '" /><span style="color:Red; width:100%;" id="' + id + 'displayTextError"></span></span><span style="float:left">' + CreateDropDown('ddl_' + id, valueFormat, hasWeights) + '</span><a class="' + ancClass + '"></a></li>';
}
else {
liObject = '<li newtext="' + newText + '" valueFormat="' + valueFormat + '" scaleID="' + scaleID + '" scaleType="' + scaleType + '" hasWeights="' + hasWeights + '" customColumnType="' + customColumnType + '" class="" id="' + id + '"><span id="span_' + id + '" title = "' + html + '">' + getDisplayString(html) + '</span><a class="' + ancClass + '"></a></li>';
}
return liObject;
}
You can use for loop instead of jQuery.each, that will be faster. Store the itemCount before the loop, and use that:
itemCount = jsonData.items.length;
for(var i = 0; i < itemCount; i++ ) {
...
You can also use use an array instead of string concatenation, like so:
var innerList = [];
... // inside the loop
innerList.push(CreateLiWithSpans('li_' + controlId, l.QuestionText, true, false, l.ScaleID, l.ScaleType, l.HasWeights, l.CustomColumnType, l.ValueFormat));
... // after the loop
$("#itemList").html(innerList.join(''));
This will be faster in IE, I'm not sure about other js engines.
These two methods will not make a significant difference, so you should try implementing a client side pagination from json. (Not by hiding and showing divs, by rendering only visible page into the DOM).
Instead of waiting for the loop to end to append your data, why not actively append the data as you process it. This will allow the user to get immediate feedback instead of waiting for the whole thing to process. Other than this, I'd stick with my original comment to page the data.
$(jQuery.each(jsonObject.AvailableColumns, function (i, l) {
if (type == "manual") {
$("#itemList").append( '<li newText="" valueFormat="' + l.ValueFormat + '" scaleID="' + l.ScaleID + '" scaleType="' + l.ScaleType + '" hasWeights="' + l.HasWeights + '" customColumnType="' + l.CustomColumnType + '" class="" id="li_' + controlId + '"><span id="span_' + controlId + '" title = "' + l.QuestionText + '">' + getDisplayString(l.QuestionText) + '</span><a class="actionLeft"></a></li>');
}
else if (type = "exportall") {
$("#itemList2").append(CreateLiWithSpans('li_' + controlId, l.QuestionText, true, false, l.ScaleID, l.ScaleType, l.HasWeights, l.CustomColumnType, l.ValueFormat));
}
controlId++;
}));
Try replacing jQuery.each with a plain old for...in loop. Using jQuery.each adds overhead that you don't need.
Don't concatenate strings inside your loop. Instead, .push them onto an array variable and use .join('') to build the string all at once at the end.
You may need to eliminate CreateLiWithSpans as a separate function in order to fully implement (2).
Changing from using jQuery.each to a standard javascript for loop should speed it up a bit. Make sure that you save the length to a variable like this though:
for(var i = 0, len = jsonObject.AvailableColumns.length; i < len; i++){
var l = jsonObject.AvailableColumns[i];
// Continue with rest of code
}
Probably won't be a huge increase but every little helps.
Also try lowering the number of function calls you make as these have added overhead (not usually an issue, but in a large loop it can help). Unless the code is shared between functions try doing it inline and see how much that speeds it up.

Categories

Resources