Use callback function to create variables and use in a html element - javascript

Firstly excuse my ignorance with any inaccurate information I provide I a very new to javascript, jquery and json.
Anyway I have a script which pulls data from a json file and displays in a webpage with the help of javascript, jquery, ajax(i think) and json.
There is a callback for when I get back the results:
function searchCallback(data) {
$(document.body).append('<h1>' + data.title + '</h1>');
}
And it works fine the like this. However I want data.title (json object) to be displayed in a html element of my choice without having to use $(document.body) because my page won't display correctly at I have other html elements outside the script.
As far as I know (excuse ignorance) with javascript I can possible add a variable and use it as follows:
var title = data.title;
And in my html:
<span id="title"></span>
or maybe there is cleaner way?
Anyway how do I achieve this. Thank you for any help!!

If you want to find an element and modify, jQuery makes this easy. Instead of $(document.body).append find an existing element by it's id, and then call the text method on it to replace the text inside that element with something new.
$('#title').text(data.title);

Related

Using .html() to dynamically generate content but js styling is not applied after using .html()

I'm building a website to use with Cordova on mobile. I found this great javascript framework called nativedroid2. This framework generates html classes, effects and the like which are applied to html code.
Now what I am trying to do is dynamically generating html code in jQuery by using AJAX calls to a server (I want javascript to make the HTML to remove the load of the server). However when I try to use html() on some divs to load some HTML, the nativedroid javascript function does not apply to the HTML, so no styling is done and everything looks like I am not even using nativedroid2. I am not using AJAX calls yet because I was testing if the html() works with nativedroid.
var html1;
var html2;
function loadpage(id, data) {
generateContent(id, data);
$('[data-role="header"]').html(html1);
$('[role="main"]').html(html2);
}
function generateContent(id, data) {
html1 = "bunch of html for the header"
html2 = "bunch of html for the body"
Does anyone know a better alternative to html() or a fix to make this work?
Alternative for html()
You can use JavaScript function createElement()
var P_tag=$("#your_div_id").createElement('p');
This will create an element P-tag, after that, you can set text to it
P_tag.text("Text");
So I read online that I had to escape the quotation marks. I used an online tool for that. However the online tool made " into "", which is read as an empty string. Removing that fixed it.
Thank you for your time if you answered

How to optimize the creation of long html code to be used in javascript string

I need to define javascript variables containing very long html code.
Here is a short example:
var text = "Select one item:<br>";
text += "<ul class='thumbnails'><li class='span3'><a href='#' class='thumbnail'><img src='http://placehold.it/260x180' alt=''></a></li></ul>";
Since the html is going to be much much longer, I would rather work in pure html rather than append text to a javascript string.
I thought of creating a separate html file, but I guess that would require an Ajax call to fetch its content.
What is the best way to deal with this?
As N.Zakas said on "maintainable javascript" book, you should «keep html out of javascript» to promote high mantainability of the code through loose coupling of UI layers.
Beside the ajax solution you could also place the markup as a comment in the html file and read it via javascript (as a regular DOM node) or you could use some kind of microtemplating system (e.g. handlebars) and place your markup in a script block (the idea is to put markup where is expected to be found and not into javascript logic)
One possible solution is to use templates. There are a few JavaScript libraries that provide templating, underscore.js is one: http://underscorejs.org/#template, or more details on how to use it for templating http://www.headspring.com/blog/developer-deep-dive/an-underscore-templates-primer/
Plus underscore is great for a number of other things.
You could break up the text into actual HTML objects.
var thumbnailsUL = document.createElement('ul');
for (index in {your-thumbnails-list}) {
var thumbnail = document.createElement('li');
thumbnail.innerHTML = {whatever you need, more objects or html as text};
thumbnailsUL.appendChild(thumbnail);
}
Ideally though, there is no reason to build this IN JavaScript - can you not emit it from the server?
Instead of constructing HTML in Javascript as a string, I would rather suggest you to emit those html elements in the page itself and hide while loading. Then in Javascript, you could select that container and display it.

How would you refer to javascript function directly in html?

So the idea is this. I have an array in the js file as well as a function that refers to a random element from that array. I want to be able to click a button and the text in the span changes to a random element in the array.
I already have a way of doing this. I have a span with an id of "change_equivalently". Then in the javascript file, I have
var Equivalentlys = [
"Equivalently, ",
"Alternatively, ",
"Another way of saying this is that "
];
$('#shuffle').click(function() {
var length = (Equivalentlys.length + 1);
var x = Math.floor(Math.random()*length);
function Equivalently(i){
return Equivalentlys[i];
};
$('#change_equivalently').text(Equivalently(x));
});
My question is that when I write out the html code, I always have to write
<span id = "change_equivalently"> ... </span>
in order to be able to change the words up upon clicking the button.
But I want an easier way.
I tried something like
<var> Equivalently( 1 ) </var>
to see if I could refer to the javascript function, but it didn't work.
How could I go about approaching this?
First of all, the approach you're currently using is better than what you want--it separates presentation from function and is widely regarded as the best practice.
However, you can (but, as I said, probably shouldn't) include code to be called when your element is clicked:
<span onclick="doStuff()"> blarg </span>
If you just want to be able to have JavaScript code that turns into HTML (like PHP or similar templating systems), you won't be able to do it with JavaScript.
Ultimately, the best way is just to use a span to mark the content and add a click event in your script, the way you're doing right now. This is the best semantically: in the html, all you say is that that particular word/position is changeable; you specify how it changes in your code.
Do you mean this?
<script type="text/javascript">
Equivalently(1)
</script>

HTML generation in JS code

I'd like to know your thoughts about HTML code generation in my JS code.
I just think that the html.push("<tag>" + something + "</tag>") style pretty annoying.
I've already tried something with templates inside my HTML file (and put some placeholders therein), and then used its content to a replace the placeholders to my real values.
But maybe you guys have other ideas, possibly one using jQuery.
jQuery is the way to go. You can do things like this:
// create some HTML
var mySpan = $("<span/>").append("Something").addClass("highlight");
it is cross-browser compatible,
it is an easy to use syntax
There is also a templating plugin.
You can use createelement, appendchild, and innerHTML to do this.
Here's an article from A List Apart that uses these functions in the process of generating a dropdown menu.
jQuery has javascript template plugins like jBind and jTemplate. I haven't used them myself but I do recommend jQuery whenever possible.
A note on html generation, it is not searchable by search engines in most cases.
I'm a big fan of how PrototypeJS handles templates.
First you create an instance of the Template class and pass it a string containing the template HTML.
var tpl = new Template('Here is a link to #{sitename}');
Then you pass it data containing the values to replace within the template.
$('someDiv').innerHTML = tpl.evaluate( {link: 'http://www.stackoverflow.com', sitename: 'StackOverflow'} );
In the above example, I have a div with id="someDiv" and I'm replacing the contents of the div with the result of the template evaluation.
Resig has a little blog entry on creating a very lightweight template system.
There are a bunch of JQuery function that support this. In particular, you should look at append(content), appendTo(content) prepend(content) prependTo(content), replaceWith(content), after(content), before(content), insertAfter(content), and insertBefore(content).

JQuery $(document).ready() and document.write()

Firstly, is there a way to use document.write() inside of JQuery's $(document).ready() method? If there is, please clue me in because that will resolve my issue.
Otherwise, I have someone's code that I'm supposed to make work with mine. The catch is that I am not allowed to alter his code in any way. The part that doesn't work looks something like this:
document.write('<script src=\"http://myurl.com/page.aspx?id=1\"></script>');
The script tag is referencing an aspx page that does a series of tests and then spits out something like so:
document.write('<img src=\"/image/1.jpg\" alt=\"Second image for id 1\">')
The scripts are just examples of what is actually going on. The problem here is that I've got a document.write() in the initial script and a document.write() in the script that get's appended to the first script and I've got to somehow make this work within JQuery's $(document).ready() function, without changing his code.
I have no idea what to do. Help?
With the requirements given, no, you can't use document.write without really hosing up the document. If you're really bent on not changing the code, you can override the functionality of document.write() like so and tack on the result later:
var phbRequirement = "";
$(function() {
document.write = function(evil) {
phbRequirement += evil;
}
document.write("Haha, you can't change my code!");
$('body').append(phbRequirement);
});
Make sure you overwrite the document.write function before it is used. You can do it at anytime.
The other answers are boring, this is fun, but very pretty much doing it the wrong way for the sake of fulfilling the requirements given.
picardo has the approach I would've used. To expand on the concept, take a read:
$('<script/>')
.attr('src', 'http://myurl.com/page.aspx?id=1')
.appendTo('body');
Alternate style:
var imgnode = $('<img alt="Second image for id 1"/>')
.attr('src', "image1.jpg");
$('#id1').append(imgnode);
Be sure to use the attr method to set any dynamic attributes. No need to escape special symbols that way.
Also, I'm not sure what the effectiveness of dynamically generating script tags; I never tried it. Though, it's expected that they contain or reference client-side script. My assumption is that what page.aspx will return. Your question is a little vague about what you're trying to do there.
jQuery has a ready substitute for document.write. All you need to use is the append method.
jQuery('<img src=""/>').appendTo('body');
This is fairly self-evident. But briefly, you can replace the with whatever html you want. And the tag name in the appendTo method is the name of the tag you want to append your html to. That's it.
picardo's answer works, but this is more intuitive for me:
$("body").append('<img src=\"/image/1.jpg\" alt=\"Second image for id 1\">');
Also, for the script part that is being inserted with document.write(), check out jQuery's getScript() function

Categories

Resources