<script type="text/javascript">
window.alert = function(){};
var defaultCSS = document.getElementById('bootstrap-css');
function changeCSS(css){
if(css) $('head > link').filter(':first').replaceWith('<link rel="stylesheet" href="'+ css +'" type="text/css" />');
else $('head > link').filter(':first').replaceWith(defaultCSS);
}
$( document ).ready(function() {
$.getJSON("./data/data.json", function(json) {
console.log(json.length); // this will show the info it in firebug console
});
});
</script>
I know that json is my JSON object. I want to use that to manipulate my html
if it's the 1st item in my JSON object then
<div class="item active"> <!-- active only appears if it's the first item -->
<blockquote>
<div class="row">
<div class="col-sm-3 text-center">
<img class="img-circle" src="json[0].image" style="width: 100px;height:100px;">
</div>
<div class="col-sm-9">
<p>json[0].quote</p>
<small>json[0].person</small>
</div>
</div>
</blockquote>
</div>
and I want to repeat the above code n times
There are many ways to do this, but probably the easiest way would be to build a string and append it to whatever container you want it to live in.
$.getJSON("./data/data.json", function(json) {
$.each(json, function(data) {
var html = '<p>' + data.quote + '</p>' +
'<small>' + data.person + '</small>';
$('#MySuperSpecialDiv').append(html);
});
});
Please note that this won't scale well. If you are going to add much more markup than you already have, you should really consider some sort of templating alternative.
Also, if some one comes in behind you to maintain this project, you probably won't be their favorite person.
Related
When prepending or appending to an element, it literally puts the text and doesn't compile in HTML:
var banner ={
'Format': '90x120cm',
'Value': 35
};
// var premium = { key: values };
function defineProduct(data) {
var item = $('span.tooltip')[0];
console.log($('span.tooltip'));
for(var keys in data){
console.log(keys);
item.append('<div class="item"><div class="left">'+keys+':</div><div class="right ">'+data[keys]+'</div></div>');
}
}
defineProduct(banner);
HTML:
<div class="three-columns">
<div class="col">
<div class="image-holder">
<a href='' id="premium" class="tooltips">
<img src="" class="premium-img" width="85px" height="79px">
<p class="description">Cartão <br><span style="color: #ffc600;" class="different">premium</span></p>
<span class="tooltip"></span>
</a>
</div>
<!-- Same thing from above different description -->
<!-- ditto -->
</div>
Output:
What have I tried/used:
.get();
.prepend(string);
.html(string);
.text(string); <– I don't know why, but I did
document.createTextNode(string);
set a variable which contains HTML tags strings and set to one of the previous attempts
And the reason I used .get() is because I have more than one object that are equivalent to the quantity of their elements, in this case, I have 3. So, for every append, I have different information. E.g.: .get(0), .get(1), etc
Instead of
item.append....
you can use:
item.insertAdjacentHTML('beforeend',....
insertAdjacentHTML: parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position.
var banner = {
'Format': '90x120cm',
'Value': 35
};
function defineProduct(data) {
var item = $('span.tooltip')[0];
//console.log($('span.tooltip'));
for (var keys in data) {
//console.log(keys);
item.insertAdjacentHTML('beforeend', '<div class="item"><div class="left">' + keys + ':</div><div class="right ">' + data[keys] + '</div></div>');
}
}
defineProduct(banner);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="three-columns">
<div class="col">
<div class="image-holder">
<a href='' id="premium" class="tooltips">
<img src="" class="premium-img" width="85px" height="79px">
<p class="description">Cartão <br><span style="color: #ffc600;" class="different">premium</span></p>
<span class="tooltip"></span>
</a>
</div>
<!-- Same thing from above different description -->
<!-- ditto -->
</div>
</div>
You're using ParentNode.append to append a literal DOMString which is appended as a text node instead of jQuery#append here:
var item = $('span.tooltip')[0];
The [0] access the underlying DOM element in the jQuery object. Remove the [0] to use jQuery methods (or eq(0) for the first element in the selection collection as a jQuery object) on it or use Node.appendChild.
[0] needs to be removed from $('span.tooltip')[0] . It is trying to access first child of ".tooltip" span which is not available in DOM.
In a basic XHTML document which contains some information, I'd like to have a "quick-jump" type menu of sections to be able to go to the relevant section quickly.
This is a static XHTML document, so I want all the dynamic stuff done by the browser, not the server. I figured jQuery was the way to go.
I've looked at the jQuery UI stuff and accordion is the closest thing I can find, but I don't want the sections to collapse away - I want all the content showing and just a floating contents/menu.
From this:
<h2>Section 1</h2>
<p>Some information</p>
<h2>Section 2</h2>
<p>More great info</p>
I'd like to produce something like:
<ul id="menu">
<li>First section</li>
<li>Another section</li>
</ul>
<a name="section1"><h2>First section</h2></a>
<p>Some information</p>
<a name="section2"><h2>Another section</h2></a>
<p>More great info</p>
I don't mind wrapping each individual section in a div with a class or similar, but would like the process as automated as possible, so I only need to change the actual content when I amend the document.
Any ideas?
Thanks, F.
If you want to just be able to call a function to automatically create the wrappers you could do something like this:
<ul id="menu"></ul>
<div id="sectionInfo"></div>
function addSection(name, anchor, info) {
$("#menu").append("<li><a href='" + anchor+ "'>" + name + "</a></li>");
$("#sectionInfo").append("<a name='" + anchor + "'><h2>" + name + "</h2></a><p>" + info + "</p>");
}
The HTML defines the containers for the sections, then the function itself adds the content with the wrappers you want. This would work well for simple text but if your section information has HTML in it as well it could get a bit messy. In that case, you might want to look into storing sections and their info in a database.
Usage:
addSection("First section", "section1", "Some information with great content");
Edit
You could then extend this to traverse the document when it's loaded to auto call this "addSection" function.
You'll need to define your sections with a more rigid structure so it's easier to traverse. I'd suggest something like this:
<ul id="menu"></ul>
<div id="content"></div>
<div id='sections' style='display:none;'>
<div>
<h2>Section 1</h2>
<p>Some information</p>
</div>
<div>
<h2>Section 2</h2>
<p>More great info</p>
</div>
</div>
Then once the page is loaded, loop through the defined sections and call addSection() which transforms their content into what ever you want it to look like:
<script>
$(document).ready(function() {
$("#sections div").each(function() {
addSection($(this).find("h2").first().html(), $(this).find("p").first().html());
});
});
function addSection(name, info) {
var anchor = name.replace(/ /g,'');
$("#menu").append("<li><a href='" + anchor+ "'>" + name + "</a></li>");
$("#content").append("<a name='" + anchor + "'><h2>" + name + "</h2></a><p>" + info + "</p>");
}
</script>
This code is untested, but the concept should work. You could make it more efficient by moving the elements instead of copying their HTML.
Sounds like you are looking for a piece of JavaScript that generates content based on the results of a selector. Doesn't need anything fancy to accomplish, either:
function buildSectionAnchorElement(index, heading) {
var a = $("<a>");
var name = "section" + index;
$(heading).attr("name", name);
a.attr("href", "#"+name);
a.text($(heading).text());
return a;
}
var headings = $("h1,h2,h3,h4");
var sections = headings.map(function(i,e) {
var a = buildSectionAnchorElement(i,e);
var p = $(e).next("p");
var li = $("<li>");
li.append(a);
$("#menu").append(li);
return li;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="menu"></ul>
<h2>something special</h2>
<p>lorem ipsum</p>
<h2>different thing</h2>
<p>dolor kismet aha bwaha</p>
I am trying to simplify my HTML file, and I have very long scripts that consist of just HTML (templates) that I'd like to move to their own external files. This is easy for me to do when the <script> tags involve functions, but in my case it's just straight HTML. In the new external file, how do I properly type up those HTML tags? See below.
<script type="text/template7" id="myStuffTemplate">
{{#each results}}
<div class="list-block media-list">
<ul>
<li>
<a href="#" class="item-link item-content">
<div class="item-media"><img src={{this.pictures['1']}} width="80" height="80px"></div>
<div class="item-inner">
<div class="item-title-row">
<div class="item-title">{{this.name}}</div>
</div>
<div class="item-text">{{this.description}}</div>
</div>
</a>
</li>
</ul>
</div>
{{else}}
<div style="text-align:center">
<h1>Nothing yet!</h1>
<h2>Upload things you're willing to trade so you can start trading!</h2>
</div>
{{/each}}
</script>
That's the script within the HTML File. I'd like that moved into its own external file. How can one go about doing this? And do I reference it just like every other file when I link it? eg.:
<script type="text/template7" src="js/views/mystuff.js" id="myStuffTemplate"></script>
Thanks in advance.
This is not a script, it's a template made with either handlebars or moustache templates.
You can't "source" them with <script src="..."> like you can with Javascript, but they can be stored externally, then loaded and processed at runtime. This needs to be done asynchronously through an AJAX call. For example, assuming you were using jQuery, you could achieve it with the following:
// request the template
$.get('templates/products.hbs', function(rawTemplate) {
// once received, convert the raw template to a handlebars template
var template = Handlebars.compile(rawTemplate);
// compile the template with your context 'data' and set it on an element with an id
$('#someTargetId').html(template(data));
}, 'html'); // <-- tell jquery to load the file as html
Just be warned, even small templates will take some time to load, so there will be a delay between your page loading and the template loading then being displayed.
First of all, consider using a framework like Angular.js or React.js however this should work for you:
Let's suppose that you want to put that inside a div with id=items:
<div id="items"> Your code... </div>
In the html file add this, just before the <body> closing tag:
<script type="text/javascript" src="code.js"></script>
to include your code and this
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
to include jQuery.
Create a code.js file and put the following code inside:
$(document).ready( function() {
var myCode = "{{#each results}}" +
"<div class="list-block media-list">" +
"<ul>" +
"<li>" +
"<a href="#" class="item-link item-content">" +
"<div class="item-media"><img src={{this.pictures['1']}} width="80" height="80px"></div>" +
"<div class="item-inner">" +
"<div class="item-title-row">" +
"<div class="item-title">{{this.name}}</div>" +
"</div>" +
"<div class="item-text">{{this.description}}</div>" +
"</div>" +
"</a>" +
"</li>" +
"</ul>" +
"</div>" +
"{{else}} " +
"<div style="text-align:center">" +
"<h1>Nothing yet!</h1>" +
"<h2>Upload things you're willing to trade so you can start trading!</h2>" +
"</div>" +
"{{/each}}";
$( "#items" ).html( myCode );
} );
I'm making a slider for my webpage and I'm using jquery's plugin called "Cycle". I have faced a problem with accessing source of images used in slider. It's quite hard to explain so here is my code from 'head' part:
<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="jquery.cycle.all.js"></script>
<script type="text/javascript">
$('#slider').before('<ul id="pager">').cycle({
fx: 'scrollHorz',
speed: 900,
timeout: 5500,
pause: 1,
pager: '#pager',
pagerAnchorBuilder: function(idx, slide) {
return '<li><img src="' + slide.src + '" width="120" height="65" /></li>';
}
});
</script>
Here is the html part:
<div id="slider_container">
<div id="slider">
<div class="items">
<img src="1.jpg"/>
<div class="info">
<h2>Tile Nr. 1</h2>
</div>
</div>
<div class="items">
<img src="2.jpg"/>
<div class="info">
<h2>Tilte Nr. 2</h2>
</div>
</div>
</div>
<div id="pager">
</div>
</div>
In my slider div I want to display blocks, each of them containing image and some title but in pager div I want to display only the images from those blocks used in slider. I'm sure that the problem is in slide.src expression in the third javascript. How should I change that expression to get the source of an image stored in appropriate items block?
Could you set up a jsFiddle that sources the jquery files you need here?
My guess is that slide.src isn't what you want. If slide is a reference to an element in the DOM, then you access its 'source' attribute like this: $(slide).attr('src')
Updated:
Turns out 'slide' is the containing div so we need this instead:
$(slide).find('img').attr('src')
When you inspect the argument slide inside pagerAnchorBuilder-function you find slide being a div-element with class items and containing the img-element as first child-element. So you can access the img and it's src-attribute like so:
pagerAnchorBuilder: function(idx, slide) {
var source = $('img', slide).attr('src');
return '<li><img src="' + source + '" width="120" height="65" /></li>';
}
There are also some other ways of writing it, all with same result:
var source = $(slide).find('img').attr('src');
// or in native js
var source = slide.querySelector('img').getAttribute('src');
var source = slide.querySelector('img').src;
var source = slide.firstElementChild.src
Okay, once i see the answer to this, I will feel stupid. I'm certain of that.
I've created this exactly the way I want to before, but I am refactoring my code for a new version right now. I am trying to dynamically create collapsible sets in jQuery Mobile, but my html does not render right.
<div data-role="header">
<h2>Playground</h2>
</div>
<div data-role="content">
<div data-role="button" id="addprimary" data-inline="true">Add 5</div>
<div data-role="collapsible">
<h4>Collapsible</h4>
<form id="makecollapsible">
</form>
</div>
</div>
<div data-role="footer">
<h4>Please, no applause</h4>
</div>
</div>
<script>
$('#addprimary').on('click', function () {
Markup.Collapsible();
});
var Markup = new Object();
Markup.Collapsible = function () {
$('#makecollapsible')
.append($('<div>')
.attr({ 'data-role': 'collapsible-set', 'id': 'primary' })
);
for (i = 0; i < 5; i++) {
($('<div>')
.attr({ 'data-role': 'collapsible', 'data-content-theme': 'c',
'data-collapsed': 'true' })
.html('<h4>' + i +'</h4>'))
.appendTo('#primary');
}
}
</script>
Could somebody please take a look at this http://jsfiddle.net/c2jLY/ and tell me what I have wrong? My <div>s with data-role='collapsible' are not rendering as collapsibles, which is also having an effect on the HTML I am trying to put in them later on.
Help is appreciated, thanks!
Inside Markup.Collapsible function and at the end of it, add the below. For collapsible-set, you need to tell jQM that you're enhancing a .collapsibleset() and combine it with .trigger('create').
$('#makecollapsible').collapsibleset().trigger('create');
Demo
I forgot to mention that when appending items dynamically, call enhancement methods on parent element; doing so, will enhance children elements. Thus, you don't need to use .collapsible().trigger('create') for each collapsible appended.
what i show here is a simple one but working:
<script type="text/javascript">
//dynamically make 10 collapsible items and append them to the collapsible-set
var jj = "SUPER item added..";
$('[data-role="content"]').append('<div id="set" data-role="collapsible-set"></div>');
var count;
for (count=0; count < 10; count++) { // div id should be from id='c0' to 'c9'
$("#set").append('<div id="c' + count + '" data-role="collapsible">');
$("#c" + count.toString()).append('<h3>Adding element_' + count +'</h3>');
$("#c" + count.toString()).append(jj + 'count ' + count + '</div>');
}
// either one is tested working below:
// $('[data-role="content"]').trigger('create');
$( "#set" ).collapsibleset( "refresh" );
</script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<link href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
<!------------------------page 1 ListView template-->
<div data-role="page" id="page01">
<div data-role="header" data-theme="b" data-position="fixed">
<h2>-- DEMO -- </h2>
</div>
<div data-role="content" id="content">
</div>
</body>