Add absolute hyperlink URL - javascript

I have the part of the jquery code
success: function(results) {
if (results.d.Product.length > 1) {
var html = '<h3>' + results.d.Product+ '<h3>'
+ '<div>' + results.d.ProductDescription + '</div>'
+ '**' + results.d.Url + '';**
$(test).html(html);
}
I need to add a absolute address eg. http://comcast.net
How can I do that.
Thanks,
SA

Your code doesn't escape the values (unless that's done on the server).
It would be better done like this:
$(test)
.empty()
.append($('<h3 />').text(results.d.Product))
.append($('<div />').text(results.d.ProductDescription))
.append(
$('<a />')
.attr('href', "http://yourdomain.tld/" + results.d.Url)
.text(results.d.Url)
);
I assume that this is what you're trying to do. Note that you might need to remove the / from the domain name string if the URL from the server already has it.

Related

How to get Html code after javascript has modified it?

I want to get the HTML code of a webpage after it has been modified (similar to one that we see in inspect element tab of a browser) and I want to do it programatically (if possible using python or any other programming language). Can someone suggest how I might be able to proceed with this? I know its possible since browsers are able to do it.
As the server has no access to client window after client-side changes, you have to use client side languages.
In jquery:
var fullCode= "<html>" + $("html").html() + "</html>";
if you want also to include the Doctype:
var node = document.doctype;
var fullCode = "<!DOCTYPE "
+ node.name
+ (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '')
+ (!node.publicId && node.systemId ? ' SYSTEM' : '')
+ (node.systemId ? ' "' + node.systemId + '"' : '')
+ '>';
fullcode += "<html>" + $("html").html() + "</html>";
Thanks to this
Using JQuery you can achieve this by the following code
$(document).ready(function(){
var html = "<html>"+$('html').html()+"</html>";
});

Outputting data from an AJAX call to HTML

I'm using AJAX to add more articles to a list of articles when you press a button. So my AJAX call returns data that includes a title, author and 1 to 3 images associated with the article. Below is the code I'm using to output it, but it feels VERY clunky.
What are the best practices for printing out HTML with JavaScript/jQuery in a scenario like this where I need to add many new tags with new information? Thanks for the help!
Also, I know some of the code isn't super well written because it's a first draft just to make stuff work, so please only answer this question with regards to printing out the HTML or things that will make printing the HTML easier
$j.getJSON(ajaxurl, {action: 'load_articles', issues: $issues}, function(data) {
if (data.message != null) {
alert(data.message);
return
}
list = $j('.all-articles ul');
for (i in data.articles) {
article = data.articles[i];
//Hides articles already on page
if ($j("#" + article.id).size() === 0) {
list.append('<li class="article-preview" id="' + article.id + '">' +
'<h3 class="article-headline">' + article.title + '</h3>' +
'</li>');
current = $j("#" + article.id)
current.append('<p class="authors"></p>');
authors = $j("#" + article.id + " .authors")
for (a in article.authors) {
authors.append(article.authors[a].data.display_name + " ");
}
current.append('<div class="images"></div>');
images = $j("#" + article.id + " .images")
for (i in article.image) {
text = "<div class='image-expand-container'>";
if (i == 0) {
text += ('<img id="' + article.image[i].id + '"class="selected" src="' + article.image[i].medium + '"></img>');
}
else {
text += ('<img id="' + article.image[i].id + '" src="' + article.image[i].medium + '"></img>');
}
text += '<div class="dashicons dashicons-editor-expand"></div></div>';
images.append(text);
}
}
}
There are a few approaches you can take.
As you're doing here, you can return data from your ajax call (e.g. as JSON) and then use a javascript function to generate the corresponding HTML by building strings. This, as you're finding, is often messy.
You can generate the actual HTML on the server side, and have the ajax call return an HTML fragment, which you insert into your DOM. This has the advantage that, if some of your HTML is loading when the page loads, and some is loading via ajax, you can use the same approach (PHP, XSLT, ASP.NET Razor, any kind of server-side templating) to generate all of the HTML.
You can use a javascript templating framework to turn your JSON data into HTML. If all of your HTML is being generated via javascript (e.g. in a single-page application) this may be your best bet.

Create something like facebook wall

I want to create something like Facebook wall. Currently I am getting the data in a json format and displaying using jQuery $each and then appending it to the main div. I am looking for an alternative way of doing this.
The problem in the current code is that i cannot use the div class to call any method like on.click . The on.click method need to be inside the $each to be get called and it gets called the number of object present in data.
And if i want to update the wall then i need to update the data and has to refresh the whole structure. Is there any other way by which i can add the new post to the wall without rebuilding the structure.
$.each(data, function () {
var status_id = this['Id'];
var like_id = "like" + status_id;
var commennt_id = "commnet-tem" + status_id;
var likes = 0;
$("<div class=\"post-indi\" id=\"post-item" + status_id + "\">" +
"<div class=\"post-content\">" +
" <div class=\"status-profile\" >" +
"<img src="">" +
"</div>" +
"<div class=\"content\">" + this['status'] + "</div>" +
"</div>" +
"<div class=\"commentbox-info\">" +
"<a id=\""+like_id+"\" href=\"#\" class=\"postddlike\">Like</a><img </div></div>").appendTo("div.post");

Selecting an image isn't working

I got some troubles working on javascript for an Firefox OS app, so I hope anyone can help me.
The case is I append some images from javascript (see code)
var aux = "<img class=\"imageOn\" id=\"" + imageName + "\"" + "src:\"" + imageURL + "\" >";
var image = "<a class=\"imageOn\" href=\"#\"> " + aux + " </a>";
$("#categoriasList").append(image);
$('#'+imageName).attr('src',imageURL);
And now I want to select one of these images from another js file:
$("img.imageOn").bind('click', function(e) {
console.log($(this).attr('id'));
playText($(this).attr('id'),"es");
// Change to picturesView
// Load icons from category choosed
});
The point is that actually it isn't working, the event is not triggered, so apendding or selecting the images has to be wrong, but I don't find the error. Does anyone know how to fix it?
Thank you in advanced.
Your src attribute should be followed by a = not a :
"<img class=\"imageOn\" id=\"" + imageName + "\"" + "src=\"" + imageURL + "\" >";
This
"src:\"
Should probably be
"src=\"
You need a = instead of : in your src. Try this:
"<img class=\"imageOn\" id=\"" + imageName + "\"" + "src=\"" + imageURL + "\" >";
If your are using jQuery you can use following method.
var aux= $(document.createElement('img')).attr(
'id':imageName,
'src':imageURL,
'class':'imageOn'
),
image = $(document.createElement('a')).attr({
'class':'imageOn'
'href':'#',
});
image.html(aux);
$("#categoriasList").append(image);
And after appending you can attach event handler. If you attaching without creating actual element it will not be triggered. It means if you want to attach event handler in the different file you should be sure that all elements already created. Otherwise there will not be triggered.
I fixed it using the event handler "on" of query

What is the fastest way to build HTML from JavaScript?

I am working on a website that uses infinite scroll. There is a function called is_element_in_view() that gets executed on these 3 events:
scroll
load
resize
The function does exactly what it's called, it checks to see if an element with a loading gif image is in view and if so it fires an ajax request to get content from the server.
The server sends back a json object that looks like this:
[{
"url": "\/embed\/182926\/some-slug",
"thumb": "http:\/\/cdn.site.com\/91\/26\/a62c1ad74327321dab78bb194c130da5.jpg",
"type": "video",
"is_original": false,
"is_prank_news": false,
"title": "Hello World",
"description": "\t<p>Enjoy this video!<\/p>",
"teaser": "Click Me!",
"finder": "Found by <strong>Jim<\/strong> yesterday",
"likes": "2 likes",
"ad_img": null,
"media_stats": "<div class=\"media-status\">2000 views<\/div>"
},
more objects...]
There's only one object in this response for clarity sake but in reality I get back 20. This is how I'm building out the html from the json data:
$.ajax({
url: '/some/ajax/url',
type: 'get',
data: 'somedata',
dataType: 'json',
success: function(response) {
if(!$.isEmptyObject(response)) {
for(var i = 0; i < response.length; i++) {
if(response[i]) {
var item = response[i];
var title = item.title.replace(/\\"/g, '"');
var media_label = '';
var item_description_teaser = '';
var likes = '';
var ad_image = '';
var media_stats = '';
if(item.description) {
// description
item_description_teaser = '<div class="description">' + item.description.replace(/\\"/g, '"');
// teaser
item_description_teaser += (item.teaser) ? ''+ item.teaser.replace(/\\"/g, '"') +'<img src="images/teaser-arrow.png" alt="" /></div>' : '</div>';
}
// media label
if(item.type == 'article' && item.is_prank_news || item.is_original && item.is_prank_news) {
media_label = '<span class="media-label prank-news-network">Prank</span>';
}
else {
if(item.type == 'article') {
media_label = '<span class="media-label article">Article</span>';
}
else if(item.is_original) {
media_label = '<span class="media-label original">Original</span>';
}
}
// likes
if(!settings.hide_likes) {
likes = '<span class="likes">' + item.likes + '</span> | ';
}
// ad image
if(item.ad_img) {
ad_image = '<img src="'+ item.ad_img +'" alt="" class="ad-img" />';
}
block += '<article class="block">' +
'<div class="inner-left">' +
media_label +
'<a href="'+ item.url +'" title="" class="thumb">' +
'<img src="'+ item.thumb +'" alt="" width="198" height="111" />' +
'</a>' +
'</div>' +
'<div class="inner-right">' +
'<a href="'+ item.url +'" title="" class="title">' +
title +
'</a>' +
item_description_teaser.replace(/\\"/g, '"') +
'<div class="media-stats">' +
likes +
'<span class="finder">'+ item.finder.replace(/\\"/g, '"') +'</span>' +
'</div>' +
ad_image +
'</div>' +
item.media_stats +
'</article>';
}
}
$('#content').append('<div class="page page-'+ page_num +'">' + block + '</div>');
// update page count
page_num++;
// clear previous listings
block = '';
}
else {
$('#content').append('<div class="page page-1"><p class="nothing-to-show">Nothing found...</p></div>');
}
},
error: function() {
alert('error');
}
});
As you can see I put everything in one giant string stored inside the variable block. I append data to this string with every loop and append it to the page outside the loop at the end.
I feel like there is a faster way to build html from js. I read somewhere a while ago that building giant strings like I'm doing isn't as efficient as some other method the article described that I forgot. So what's the faster way to do this?
Store the blocks in an array say blocks, then
$('#content').append(blocks.join(""));
Edit: that wasn't what the OP wanted. I guess the problem is appending the stuff each time the event is triggered.
I'd say to create a DocumentFragment, put the new stuff in it, then appending to $("#content"). Unfortunately, DocumentFragments don't support innerHTML.
So, create a dummy element, fill it and then put its child nodes into the container:
var dummy = $("<div>").html(block), content = $("#content");
$.each(dummy.children(), function(i, c) {content.append(c);});
Adding html elements to the DOM represents a big performance penalty so it is better to create a big string and append it at the end, this post explains it really well
For most of your uses, the method of creating one really long string and appending it at the end will be the best choice, as it makes the best use of the trade offs of code legibility, ease of programming, and speed.
You could have your server return the values already marked-up in HTML, then:
$('#content').append( response );
You can then handle all of your looping and filtering server side, cutting down on the amount JS in your document.

Categories

Resources