Loading HTML dynamically using JavaScript (class.js) - javascript

I am working on building an application which has a few HTML components.
Use Case:
I am trying to achieve something similar what is present here. I want to call the HTML components on click of a menu and apply some actions like drag and resize, etc.
Research:
I was advised to take an object-oriented approach for building the application and hence while going through Google came across class.js for JavaScript inheritance.
I went through the initial tutorials, but I am not sure how and where can I store the HTML initially that will hold the structure for the HTML components?
In the reference application they have used backbone.js and require.js, but I am a bit short on time to learn these.
My Work So Far:
What I have tried is creating a file components.js and creating the outer HTML structure for a component like this:
var textBox = '<div class="structure-textBox">
<div class="editable">
<p><span style="font-size:20px;"><span style="font-family: arial,helvetica,sans-serif;"><strong>Text Box</strong></span></span></p>
<ol>
<li><span style="font-size:14px;">Double Click on the <strong>Text Box</strong> to Edit Text.</span></li>
<li><span style="font-size:14px;">For easy use of the text editor click on the "i" (to the left of the x close) and watch a 30 sec video tutorial.</span></li>
</ol>
<p><span style="font-size:14px;"><span style="color:#7cba0c;">Enjoy web designing with GoBiggi.</span></span></p>
<p><span style="font-size:14px;">Click on the <strong><u>Design Assistance</u></strong> link for further help.</span></p>
</div>
</div>';
This is a text box stored in a JavaScript variable that I want to add when user clicks on a menu. But how can it be achieved using class.js's inheritance pattern?
I have a canvas page created and menus for the components. Now I am stuck at this part of getting the html content and displaying it on the canvas.

I don't see that what you're asking has anything to do with inheritance.
There are several simple ways to put something on your web page using JavaScript.
For instance, if you have the following on your page somewhere <div id='target'></div>, you could write this:
var textBox = '<div class="structure-textBox">
<div class="editable">
<p><span style="font-size:20px;"><span style="font-family: arial,helvetica,sans-serif;"><strong>Text Box</strong></span></span></p>
<ol>
<li><span style="font-size:14px;">Double Click on the <strong>Text Box</strong> to Edit Text.</span></li>
<li><span style="font-size:14px;">For easy use of the text editor click on the "i" (to the left of the x close) and watch a 30 sec video tutorial.</span></li>
</ol>
<p><span style="font-size:14px;"><span style="color:#7cba0c;">Enjoy web designing with GoBiggi.</span></span></p>
<p><span style="font-size:14px;">Click on the <strong><u>Design Assistance</u></strong> link for further help.</span></p>
</div>
</div>';
document.getElementById('target').innerHTML = textBox;
For best results, I would suggest learning to use a library like jQuery. These tools are designed to make it easier to manipulate the HTML of the page, among other things.

Related

Trying to build a content locker using jQuery

I am very new to jQuery and not entirely sure what I'm doing. Will try my best to explain the problem I'm facing.
I'm trying to lock some content on a landing page until a user shares the link using FB, Twitter, LinkedIN or G+. The first version of the script I wrote (which worked fine) ran like this:
<head>
<script type="text/javascript">
...
$(document).ready(function()
{
$('.class').click(clearroadblock());
buildroadblock();
}
</script>
<style>
.class
{
[css stuff]
}
</style>
</head>
<body>
<div id="something">
<ul>
<li> Link1 </li>
<li> Link2 </li>
</ul>
</div>
</body>
The problem I'm now facing is changing out this code to replace the list elements with social share buttons. As they are no longer under .class, but classes like fb-share-button and twitter-share-button. Please help me understand what I need to modify to accommodate this? PS: This is not a Wordpress site.
function clearroadblock()
{
$('#roadblockdiv').css('display', 'none');
$('#roadblockBkg').css('display','none');
}
This is the way I'm clearing the overlay once a click is detected, BTW.
Can I wrap the social buttons in divs, assign them IDs and use those IDs to trigger the click like below?
<div id="Button">
Tweet
</div>
$('#Button').click(clearroadblock());
You can have multiple classes on an element by separating them with a space. Try the following:
class="class fb-share-button"
Your jquery will still work off the "class" class. I would recommend you change this name to something more meaningful though. Your css can target the "class" for general styles, but you can also target fb and twitter separately.
Update
I decided to create a quick JSFiddle for this.
Some of the styles etc won't be the same as what you're doing, but the problem is resolved. I've created a div with id main that contains the content that you want to hide. There's an absolutely positioned div over the top of this, this is the roadblock. The javascript is showing the roadblock (assuming that's what you wanted to do with buildroadblock()).
On click of a link in the ul with id socialMedia we call clearroadblock. Notice the lack of parenthesis. This hides the roadblock.
This isn't a great way of preventing someone from seeing information, you might want to think about pulling the content down from the server when the action is performed, however, I think this answers your question.

How can I use Angular to create interactive widgets from vanilla (non-Angular) HTML?

I'm building an Angular application: a training engine which will present online courses to the user.
Each course is basically a series of "slides" - HTML partials which the user can navigate through in sequence. Each slide can include zero or more interactive widgets of varying types: simple quizzes, hands-on exercises, etc.
My goal is for the courses to consist of pure HTML/CSS, so that less technical folks can build courses without having to get their hands dirty with JS or Angular. That's fine as long as courses only contain static HTML. But it gets tricky when I want to add the interactive widgets to a course.
For example, a sample course "slide" might look like this:
<p>Here's some static content introducing the quiz.</p>
<div class="quiz">
<ol class="questions" data-passing-score="50">
<li>
<p>What was Abraham Lincoln's last name?</p>
<ul class="answers">
<li>Smith</li>
<li>Johnson</li>
<li class="correct">Lincoln</li>
<li>Liebowitz</li>
</ul>
</li>
<li>
<p>What were George Washington's false teeth made of?</p>
<ul class="answers">
<li>Particle board</li>
<li class="correct">Wood</li>
<li>The bones of his enemies</li>
<li>Advanced space-age polymers</li>
</ul>
</li>
</ol>
</div>
<p>Here's some static content that appears after the quiz.</p>
...and, when this HTML file gets loaded (presumably via $http.get()), my application would notice that it contains a div with the class quiz, and would set up the needed interactivity: tweaking the structure of the markup (e.g., adding radio buttons and a submit button), perhaps hiding and showing elements (so the user would only see one question at a time), scoring the quiz on submission, etc.
This is a pretty common pattern in jQuery-land. Of course, we're not in jQuery-land.
If I'm thinking about this correctly, there are two problems I would need to solve to make this work.
Problem 1: First, I would need to get the quiz data out of the raw HTML, and into a JavaScript object. For example, I might parse the HTML above into a structure like this:
var quiz = {
passing_score: 50,
questions: [
{
ask: "What was Abraham Lincoln's last name?",
answers: [
{ text: "Smith", correct: false },
{ text: "Johnson", correct: false },
{ text: "Lincoln", correct: true },
{ text: "Liebowitz", correct: false }
]
},
...
]
};
I guess I'd want to convert the loaded HTML into a DOM tree (just in memory, not appended to the document), and then explore it (using jQuery or jqLite) to find the data I'm interested in.
Is that a sensible approach? Are there other approaches I might want to explore?
Problem 2: Second, I would need to replace div.quiz in the loaded HTML with the contents of a quiz template, like this:
<form ng-controller="QuizController as quizCtrl" ng-submit="quizCtrl.submit()">
<ol>
<li ng-repeat="question in quizCtrl.questions">
<p ng-bind-html="question.ask"></p>
<ul>
<li ng-repeat="answer in question.answers">
<label>
<input type="radio" ng-attr-name="{{ 'q' + $parent.$index }}" ng-model="question.selected_answer" ng-value="answer">
<span ng-bind-html="answer.text"></span>
</label>
</li>
</ul>
</li>
</ol>
<button type="submit">Score Quiz</button>
</form>
...and bind that div to QuizController.
How do I dynamically bind a particular DOM node to a particular controller? How do I get the quiz object (which I constructed in the previous step) into the controller's scope?
Is there a standard-ish solution to this problem in Angular-land? Or is this entire approach just totally bananas?
Hope this makes sense. Thanks for any guidance you can provide!
The answer, as #dandavis suggested in the comments above, is custom directives.
For my quiz example, I could create a custom directive that defines a custom element. (Alternately, I could use restrict: 'C' in my directive definition to match <div class="quiz">, or restrict: 'A' to match on <div quiz>.)
Then, I just would put all my setup-and-DOM-massaging logic in the directive's link function.
Finally, I would just need to specify to the course authors how they should mark up a quiz.
I haven't fully played this out in real code yet, but I'm pretty sure this is all accurate.

Formatting dynamically formed HTML elements created after Script is run

So this is actually a very tricky concept to portray so here is my attempt.
I am utilizing an HTML form template in LANDesk Service Desk - tool is irrelevant but important to note that there is back-end code that I cannot touch that is generating HTML.
So basically, the tool is pulling data from a back-end database containing a list of objects. It then inputs this data into an HTML form template that I have created using variables as placeholders for the objects. The HTML is then built on the fly with however many objects are in the database. Thus, I have no way of accessing the head - (which means native JS, and inline CSS).
My template looks like this...
<div class="my-template">
<a class="my-template my-link">My Link</a>
</div>
<script>
var myLinks = document.getElementsByClassName('my-link');
for (var i = 0 ; i < myLinks.length ; i++) {
myLinks[i].style.display = "none";
}
</script>
When I view the source on the loaded page it looks something like this...
<body>
<!--misc. page stuff-->
<!--First Item-->
<div class="auto-create">
<div class="my-template">
<a class="my-template my-link">My-Link</a>
</div>
</div>
<!--Second Item-->
<div class="auto-create">
<div class="my-template">
<a class="my-template my-link">My-Link</a>
</div>
</div>
</body>
All of the elements are formatted the way I want them to be...besides the last element on each page. I have determined that this is because each time the tool is running the object through the template, it is running the script. The issue is, there is a stupid default button that they place at the bottom of each object that is broken. (This is why I have the script changing the style to display: none..should have mentioned this earlier). Basically I want to delay the execution of the script until not only the object has been run through the template...but the entire page has loaded...but I can't seem to get the last button to go away.
I know that this is a lot of poorly written words trying to form an explanation, but I really think this is impossible...but I am convinced there has to be a way. (Also, the company isn't providing us with any help in finding a workaround, so I had to basically MacGyver this one

How to create an HTML module angular

Learning HTML/Angular.
I have a bunch of HTML code that I want to be re-usable. Basically I write it once and modify the same code base, then just insert the dynamic data using Angular.
My question is - How do I create re-usable HTML code that can be injected into a page using Angular?
For instance, lets say I am an app developer and want to showcase 25 apps on the same page each with their own HTML component (not just a bunch of images). Rather than copying the HTML 25 times I would just like to inject that HTML snippet via some angular command, then insert the text into the corresponding divs etc. I need to stick with Angular/HTML (no other frameworks)
Or is there a better way?
(look at the image for reference - imagine inserting that layout 25 times without duplicating code)
I have tried this using ng-repeat but when I do so it throws the repeating items in the same spot on top of each other. I was hoping that for every div that is repeated it would put it underneath the other div.
<div id="apps" ng-controller="MyApps">
<div id="appsection" ng-repeat="app in applist">
<img class="rightappimg" src={{app.img}} />
<strong class="appbannertext">{{app.firstLine}}</strong>
<strong class="appbannertextsubtitle">{{app.secondLine}}</strong>
<strong class="appbannertextsubtitlesmall"><span class="ios">iOS, iPhone, iPad</span> & <span class="android"> Android</span></strong>
<strong class="appbannerdescriptiontitle">{{app.fourthLine}}</strong>
<p class="appbannerdescription">{{app.fifthLine}}</p>
</div>
</div>
Ok the answer was to us ng-repeat as such:
<div id="apps" ng-controller="MyApps">
<div id="appsection" ng-repeat="app in applist">
<img class="rightappimg" src={{app.img}} />
<strong class="appbannertext">{{app.firstLine}}</strong>
<strong class="appbannertextsubtitle">{{app.secondLine}}</strong>
<strong class="appbannertextsubtitlesmall"><span class="ios">iOS, iPhone, iPad</span> & <span class="android"> Android</span></strong>
<strong class="appbannerdescriptiontitle">{{app.fourthLine}}</strong>
<p class="appbannerdescription">{{app.fifthLine}}</p>
</div>
And then simply to specify a min-height in the div id in the CSS file so the items wouldn't overlap each other.

JavaScript: How should I generate a lot of HTML? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is there a best practice for generating html with javascript
I want to generate large parts of a website with JavaScript.
The straightforward way is to form one large string containing all the HTML:
'<div>'
+ '<span>some text</span>'
+ '<form>'
+ '<input type="text" />'
...
But this gets quite annoying when one has to write a few hundred lines in this style. And the pain when such code has to be changed later on...
Can you think of an easier way?
Create snippets as templates, put them into an invisible <div>:
<div style="display: none">
<div id="template1">
<h2 class="header_identifyingClass">Hello from template</h2>
</div>
<div id="template2">
<span class="content">Blah blah</span>
</div>
</div>
Then find it,
document.getElementById("template1");
fill it's internal values, e.g. find inside elements by XPath or jQuery and fill them e.g. using element.innerHTML = "Hello from new value", and move or copy it to the visible part of DOM.
Create multiple templates and copy it multiple times to generate many.
Don't forget to change the ID for copies to keep it working.
PS: I think I used this approach in the code of JUnitDiff project. But it's buried in XSLT which serves another purpose.
By far the best way to do this is to use some kind of JavaScript templating system. The reason why this is better than hiding HTML with CSS is that if (for example) someone has CSS disabled, they'll be able to see your templates, which is obviously not ideal.
With a templating system, you can put the templates in a <script> tag, meaning that they're totally hidden from everything except JavaScript.
My favourite is the jQuery templating system, mostly because jQuery is so ubiquitous these days. You can get it from here: http://api.jquery.com/category/plugins/templates/
An example (taken from the jQuery docs):
<ul id="movieList"></ul>
<!-- the template is in this script tag -->
<script id="movieTemplate" type="text/x-jquery-tmpl">
<li><b>${Name}</b> (${ReleaseYear})</li>
</script>
<!-- this script will fill out the template with the values you assign -->
<script type="text/javascript">
var movies = [
{ Name: "The Red Violin", ReleaseYear: "1998" },
{ Name: "Eyes Wide Shut", ReleaseYear: "1999" },
{ Name: "The Inheritance", ReleaseYear: "1976" }
];
// Render the template with the movies data and insert
// the rendered HTML under the "movieList" element
$( "#movieTemplate" ).tmpl( movies )
.appendTo( "#movieList" );
</script>
It's a simple example, but you could put all of the HTML you'd like to generate in the <script>, making it much more flexible (use the same HTML snippet for various jobs, just fill out the gaps), or even use many templates to build up a larger HTML snippet.
Use a dialect of JavaScript such as CoffeeScript. It has heredocs:
'''
<div>
<span>some text</span>
<form>
<input type="text" />
'''
If you need to throw in an occasional expression, you can use interpolations:
"""
<title>#{title}</title>
"""
If it's static content that you're just adding to the page on a javascript event, you could consider simply having it in your main HTML page all along, but style with display:none;.
Then it's just a case of changing it's style to make it appear on the page. Much easier.
Even if it's dynamic, you could use this technique: have the shell HTML content there hidden in your page, and populate the dynamic bits before making it visible.
hope that helps.

Categories

Resources