HTML functions? [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a repeated HTML code, like:
<figure class="print">
<a href="#">
<img src="images/5.png" alt="" />
<dl>
<dt>Client</dt>
<dd>Envato</dd>
<dt>Role</dt>
<dd>Print</dd>
</dl>
</a>
</figure>
Is there a smart way to make a 'function' out of it (that accept the captions and image as parameters), or do I need to repeat that code so many times?

with HTML you don't have the possibility to write functions that generate what you want. It seems that you would like to generate dynamic content. This is usually done by employing a scripting language.
So you have two options here:
Use a server side scripting language like PHP
If you want a client side solution you could use JavaScript which can dynamically create content for you.
For further information just Google for some simple tutorials.

There are no way in pure HTML.
You can use JavaScript(jQuery) or back-end script, like PHP.
$("html").append($(".print").clone());

As other people have said, HTML is a declarative language. However, with modern frameworks like AngularJS, you can write things like:
<figure class="print" ng-repeat="figure in figures">
<a href="#">
<img ng-src="{{figure.image}}" alt="" />
<dl>
<dt>Client</dt>
<dd>{{figure.captions.client}}</dd>
<dt>Role</dt>
<dd>{{figure.captions.role}}</dd>
</dl>
</a>
</figure>
The corresponding model would be:
var figures = [{
image: 'images/5.png',
captions: {
client: 'Envato',
role: 'Print'
}
}, {
image: 'images/6.png',
captions: {
client: 'Another caption',
role: 'Print'
}
}];
It takes some time to get used to it, but you should read the code of their TODO example app.

Try using jquery template.
<script src="jquery.tmpl.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var data = [
{ name: "Astor", product: "astor", stocklevel: "10", price: 2.99},
{ name: "Daffodil", product: "daffodil", stocklevel: "12", price: 1.99},
{ name: "Rose", product: "rose", stocklevel: "2", price: 4.99},
{ name: "Peony", product: "peony", stocklevel: "0", price: 1.50},
{ name: "Primula", product: "primula", stocklevel: "1", price: 3.12},
{ name: "Snowdrop", product: "snowdrop", stocklevel: "15", price: 0.99},
];
$('#flowerTmpl').tmpl(data).appendTo('#row1');
});
</script>
<script id="flowerTmpl" type="text/x-jquery-tmpl">
<div class="dcell">
<img src="${product}.png"/>
<label for="${product}">${name}:</label>
<input name="${product}" data-price="${price}" data-stock="${stocklevel}"
value="0" required />
</div>
</script>

You can do this with underscore templates, for example:
<script src="http://documentcloud.github.io/underscore/underscore-min.js"></script>
<script id="template" type="text/html">
<% data.forEach(function(item){ %>
<figure class="print">
<a href="#">
<img src="<%= item.src %>" alt="" />
<dl>
<dt>Client</dt>
<dd><%= item.client %></dd>
<dt>Role</dt>
<dd><%= item.role %></dd>
</dl>
</a>
</figure>
<% }); %>
</script>
<div id="container"></div>
In your JavaScript:
var data = [
{
src: 'images/5.png',
client: 'Envato',
role: 'Print'
},
{
src: 'images/4.png',
client: 'Foo',
role: 'Bar'
}
];
var template = document.querySelector('#template').innerHTML;
var html = _.template(template, {data: data});
document.querySelector('#container').innerHTML = html;

Related

How to make a hyperlink show in a different line

Hi i am making a books website and im trying to add a hyperlink using href but it comes up in the same line is there any way to make it to show in a different line?here is how it shows up right now
const petsData = [{
name: "Story Book",
species: "Jean Lumier",
favFoods: ["wet food", "dry food", "<strong>any</strong> food"],
birthYear: 2016,
href: "https://media.sproutsocial.com/uploads/2017/02/10x-featured-social-media-image-size.png",
photo: "https://nice-assets.s3-accelerate.amazonaws.com/smart_templates/e639b9513adc63d37ee4f577433b787b/assets/wn5u193mcjesm2ycxacaltq8jdu68kmu.jpg"
},
{
name: "Barksalot",
species: "Dog",
href:"https://www.amazon.in/Redmi-9A-2GB-32GB-Storage/dp/B08696XB4B/ref=gbph_img_m-2_0ec7_a9c5af13?smid=A23AODI1X2CEAE&pf_rd_p=cbec21a0-e969-48e2-8697-caf621220ec7&pf_rd_s=merchandised-search-2&pf_rd_t=101&pf_rd_i=1389401031&pf_rd_m=A1VBAL9TL5WCBF&pf_rd_r=7N08PRZ1WREYVED1R3Q4",
birthYear: 2008,
photo: "https://learnwebcode.github.io/json-example/images/dog-1.jpg"
},
{
name: "Meowsalot",
species: "Cat",
favFoods: ["tuna", "catnip", "celery"],
birthYear: 2012,
photo: "https://learnwebcode.github.io/json-example/images/cat-1.jpg"
}
];
//empty space thing (ㅤ)
function petTemplate(pet) {
return `
<div class ="image-grid">
<div class="animal">
<img class="pet-photo " src="${pet.photo}">
<div class="olay">
<h2 class="pet-name">${pet.name}
//href here
<h1 class="species">${pet.species}
<a href= ${pet.href}> Read Reviews</a>
<div></div></div>
</div>
</div>
`;
}
(Sorry english is not my main language)
There are several simple ways to achieve this:
Perhaps the easies it to wrap your link in a div
<div><a href= ${pet.href}> Read Reviews</a></div>
Another option is to have br tag before the link <a href= ${pet.href}> Read Reviews</a>
The most standard way to achieve your task might be to use flexbox in your CSS style read more about flexbox here https://www.w3schools.com/css/css3_flexbox.asp
Try this
<div class ="image-grid">
<div class="animal">
<img class="pet-photo " src="${pet.photo}">
<div class="olay">
<h2 class="pet-name">${pet.name} </h2>
//href here
<h1 class="species">${pet.species} </h1>
<a href= ${pet.href}> Read Reviews</a>
</div>
</div>
</div>
Or you can wrap h2, h1 and the a tag in its own div
You have to close your <h1> and <h2> tags (with </h1> and </h2>, not with </div>!)

Vue Js displaying object in qoutes

i faced an issue. I have an array of "Lessons" in which i have stored 5 objects. Each of them have parameter (url). Example:
Lessons: [
{
url: "../assets/Math.png",
Title: "Lesson",
Subject: "Math",
Location: "London",
Price: "£100",
Spaces: 5,
},
Now i did v-for to display each of them, everything is working except i dont know how to show the image i have in the /assets folder. i have tried simple way img src=" {{ lesson.url }}" and this one:
<div class="col-md-6 col-lg-3" v-for="lesson in Lessons" :key="lesson.id">
<div class="card" >
<img src="'${lesson.url}'" alt="" class="card-img-top img-fluid">
can anyone suggest me how to do it?
To use image routes in this way you must first import them for Webpack to be able to process them from the data:
import mathImg from "../assets/Math.png"
// in your data
Lessons: [
{
url: mathImg, // use the import name
Title: "Lesson",
Subject: "Math",
Location: "London",
Price: "£100",
Spaces: 5,
}
]
in your template
<img :src="Lessons.url" />
I believe you want to bind the src attribute like so:
<img :src="lesson.url" ...>
I guess you forgot the :
<img :src="`${lesson.url}`" alt="" class="card-img-top img-fluid">
and you also can
<img :src="lesson.url" alt="" class="card-img-top img-fluid">

Drag and sort divs using jQuery and output html code

What i'm doing:
I'm creating a Mailings Generator. This simply is an application, that generates Mailings (An E-mail with some of my products as advertisement) from a Mailing Template.
What i want:
I want to be able to order the divs generated in my Mailing Generator and create a new file with the new order.
Let me show you the concept:
$( "#sortable" ).sortable({
connectWith: ".connectedSortable",
stop: function(event, ui) {
$('.connectedSortable').each(function() {
result = "";
($(this).sortable("toArray"));
$(this).find("div").each(function(){
result += $(this).text() + "<br />";
});
$("."+$(this).attr("id")+".list").html(result);
});
}
});
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script src="https://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
<div id="sortable" class="connectedSortable">
<div class="companyLogo">
<!-- logo here...-->
</div>
<div class="productBox1">
Product Name: 1
Price: 10,00
<!-- etc...-->
</div>
<div class="productBox2">
Product Name: 2
Price: 20,00
<!-- etc...-->
</div>
<div class="productBox3">
Product Name: 3
Price: 30,00
<!-- etc...-->
</div>
<div class="productBox4">
Product Name: 4
Price: 40,00
<!-- etc...-->
</div>
<div class="footerInformation">
<!-- Footer Info Here...-->
</div>
</div>
<div class="sortable list"></div>
So here's a quick example of how the mailing could look when generated. (Please run the code snippet)
I want to drag the divs and sort them the way i'd like.
After i sorted them i want to create a NEW file but this time display the divs in the order i sorted the last one.
Question:
When i move the div's, i get the new order as output. What i want is it to output all the html code. This way i want to create a new file with the new order.
If there is any way to do this and you know how, please consider helping me a little. Please correct me in any way possible. it helps me learn!
If i wasn't clear enough, please let me know.
Could you be a little more specific? Send the modified HTML back to the webserver using ajax, how would i do that?
You could for example add a Button. Then when u are done sorting your articles in the list you will click that button. The eventhandler attached to that button will then extract the html that you want to save to a file (htmlToSend) from the $('#sortable') element and send it to a certain server_address.
$( "#sortable" ).sortable({
connectWith: ".connectedSortable",
stop: function(event, ui) {
$('.connectedSortable').each(function() {
result = "";
$(this).sortable("toArray");
$(this).find("div").each(function(){
result += $(this).text() + "<br />";
});
$("."+$(this).attr("id")+".list").html(result);
});
}
});
$('#send').on('click', function() {
const htmlToSend = $('#sortable').html();
alert('SENDING HTML: ' + htmlToSend);
$.ajax({
method: 'POST',
url: '<SERVER_ADDRESS>', //CHANGE SERVER_ADDRESS to the address of the script that will handle the html (save it to file or send it via email)
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify({ html: htmlToSend }),
success: function(response) {
//code to execute if saving on server was successful
},
error: function(err){
//code to execute if saving on server failed
}
});
});
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script src="https://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
<div id="sortable" class="connectedSortable">
<div class="companyLogo">
<!-- logo here...-->
</div>
<div class="productBox1">
Product Name: 1
Price: 10,00
<!-- etc...-->
</div>
<div class="productBox2">
Product Name: 2
Price: 20,00
<!-- etc...-->
</div>
<div class="productBox3">
Product Name: 3
Price: 30,00
<!-- etc...-->
</div>
<div class="productBox4">
Product Name: 4
Price: 40,00
<!-- etc...-->
</div>
<div class="footerInformation">
<!-- Footer Info Here...-->
</div>
</div>
<input type="button" value="Send to Server" id="send">
On the serverside you will need to receive that data from the post-body of the http-request. For example on a php-server u would use file_get_contents('php://input') to receive that. But that is dependant on your serverside technology that you use. So let me know if u have problems with the serverside implementation.

Using the same controller for two identical divs with different data and using xeditable for second div

So I'm trying to duplicate the section div (so I can have multiple sections with multiple articles). I tried using the same controller for both divs as shown below. So I'm able to add the section by appending it to main but I can't edit the second div. Is there any way around this?
I am not using bootstrap and i'm using xeditable.
HTML:
<div id="main" ng-app="main">
<div class = "section" ng-controller="newsController">
<h2 id="section" editable-text="sections.section">{{sections.section}}</h2>
<div class = "article" ng-repeat="article in sections.articles">
<h3 id="title" editable-text="article.title"><a editable-text="article.link" href="{{article.link}}">{{article.title}}</a></h3>
<p id="publisher" editable-text="article.publisher">{{article.publisher}}</p>
<p id="orig_title" editable-text="article.orig_title">{{article.orig_title}}</p>
<p id="descr" ng-bind-html="article.description" editable-text="article.description"></p>
</div>
<div class = "section" ng-controller="newsController">
</div>
</div>
JS:
newsletter.controller('newsController',function($scope){
$scope.sections = {
section: "Faculty",
articles: [
{
title: "In __ We Trust",
link:'http://wee.com',
publisher: "Me",
orig_title:"",
description: "Description Here"
}
]
};
$scope.addItem = function(){
$scope.sections.articles.push(this.sections.articles.temp);
$scope.sections.articles.temp={};
};
)};
var newSection = '//Pretend all the tags and the attributes as above are placed here'
$("#add-section").click(function(){
var $section = $('#main').append(newSection);
});
Apologies for formatting. I'm still new to this. Thanks!
Edit: I'm also trying to make this dynamic so the user could edit the texts like the title and the publisher, etc. How would I make the added section also editable?
Try it this way, instead of appending it uses angulars natural way of repeating divs aka ng-repeat:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.sections = {
section: "Faculty",
articles: [{
title: "In __ We Trust",
link: 'http://wee.com',
publisher: "Me",
orig_title: "",
description: "Description Here"
}]
};
$scope.addItem = function() {
$scope.sections.articles.push(this.sections.articles.temp);
$scope.sections.articles.temp = {};
};
var newSection = '//Pretend all the tags and the attributes as above are placed here'
$("#add-section").click(function() {
var $section = $('#main').append(newSection);
});
});
</script>
<div id="main" ng-app="myApp" ng-controller="myCtrl">
<div class="section" ng-repeat="i in ['0','1']">
<h2 id="section" editable-text="sections.section">{{sections.section}}</h2>
<div class="article" ng-repeat="article in sections.articles">
<h3 id="title" editable-text="article.title"><a editable-text="article.link" href="{{article.link}}">{{article.title}}</a></h3>
<p id="publisher" editable-text="article.publisher">{{article.publisher}}</p>
<p id="orig_title" editable-text="article.orig_title">{{article.orig_title}}</p>
<p id="descr" ng-bind-html="article.description" editable-text="article.description"></p>
</div>
<div class="section" ng-controller="myCtrl"></div>
</div>
I Got the answer! So I applied the app to the html document and the controller to the body as opposed to the main div and made an array of sections as opposed to a singular section. I did a ng-repeat for the section div. By doing so, I added a "addsection" function where I create a section to be added to the array and the section has to have the same properties as the other ones including an empty array of articles.
HTML:
<body ng-controller="newsController">
<ul id="convenient-buttons">
<li id="add-section">Add Section</li>
<li>Select All</li>
<li><a href=# id="export" onclick="selectText('json')" ng-mouseenter="showJson=true" ng-mouseleave="showJson=false" >Send to Server</a></li>
</ul>
<div id="main">
<div class = "section" ng-repeat="section in news.sections" >
<h2 id="section" editable-text="sections.section">{{sections.section}}</h2>
<div class = "article" ng-repeat="article in sections.articles">
<h3 id="title" editable-text="article.title"><a editable-text="article.link" href="{{article.link}}">{{article.title}}</a></h3>
<p id="publisher" editable-text="article.publisher">{{article.publisher}}</p>
<p id="orig_title" editable-text="article.orig_title">{{article.orig_title}}</p>
<p id="descr" ng-bind-html="article.description" editable-text="article.description"></p>
</div>
</div>
</body>
JS:
$scope.news = {
sections: [
{
title: "Faculty",
articles: [
{
title: "In Memoriam: Eli Pearce",
link:'http://engineering.nyu.edu/news/2015/05/29/memoriam-eli-pearce',
publisher: "NYU Newsroom",
orig_title:" ",
description: "When <strong>Professor Eli Pearce</strong> passed away on May 19, 2015, a slice of Poly history passed along with him. Pearce had been affiliated with the school, then known as the Polytechnic Institute of Brooklyn, since the mid-1950s, when he conducted his doctoral studies in chemistry here. As a student, he learned with such luminaries as Herman Frances Mark, who is often called the Father of Polymer Science, and Charles Overberger, another influential chemist who helped establish the study of polymers as a major sub-discipline."
}
]
}
]
};
$scope.addSection = function(){
$scope.news.sections.temp={
title: "Section Title",
articles:[
// {
// title:"Article Title",
// link:"Link",
// publisher: "Publisher",
// orig_title: "Original Title",
// description: "Description"
// }
]
};
$scope.news.sections.push(this.news.sections.temp);
};

button should show when value is set to true but it is not

When i set the value to true under the object canPurchase the add to cart button should show. for some reason i can only get it to show when i set ng-show with an exclamation in front of it.
i am still new to angular so i dont know the terminology very well.
here is my jsfiddle link: http://jsfiddle.net/jL0c6sLc/
<body class="container" ng-app="gemStore">
<div class="product row">
<h1>Store Name</h1>
</div>
<div ng-controller="StoreController as store">
<div class="product row" ng-repeat="product in store.products">
<h3>{{product.name}}<em class="pull-right">{{product.price | currency}}</em></h3>
<button ng-show="store.product.canPurchase">Add to Cart</button>
</div>
</div>
<script data-require="angular.js#1.2.10" data-semver="1.2.10" src="http://code.angularjs.org/1.2.10/angular.js"></script>
<script src="js/app.js"></script>
here is my app.js script
(function() {
var app = angular.module('gemStore', []);
var gems = [
{ name: 'Azurite', price: 2.95, canPurchase: true},
{ name: 'Bloodstone', price: 5.95, canPurchase: true},
{ name: 'Zircon', price: 3.95, canPurchase: true},
];
app.controller('StoreController', function(){
this.products = gems;
});
})();
Basically i only want the 'add to cart' button to show when the object 'canPurchase' is set to true.
right now the only way i can get the button to show is by doing this:
<button ng-show="!store.product.canPurchase">Add to Cart</button>
it is as if the value under canPurchase doesn't do anything wither it is set to true or false.
please help me with understanding this and why it is not working properly.
You need to use
<button ng-show="product.canPurchase">Add to Cart</button>
Not store.product.canPurchase as you currently have inside the ng-repeat. I'm pretty sure it's just that. If you don't reference the individual product item, the expression is not valid.
Verified that changing this works in this jsfiddle here

Categories

Resources