Formatting dynamically formed HTML elements created after Script is run - javascript

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

Related

Javascript: Can I Use JS to Copy an HTML Element From One Page to Another?

New to JS. Couldn't find any good solutions for this after researching, and seems like it shouldn't be too complicated.
Say I have a page called page1.html with this code:
<div class="page1">
<div class="wrapper">
<p>Some text.</p>
</div>
</div>
Now, I have a second page, page2.html, with this code:
<div class="page2">
</div>
I want to make a copy of the div with class wrapper from page1.html, and insert it into page2.html, within the div with class page2.
Both pages share the same script.js file.
I tried something like this:
page1content = document.querySelector('.wrapper');
page2content = document.querySelector('.page2');
page2content.append(page1content);
However, I'm getting errors on page1.html because the js can't find the div with class page2, and I'm getting errors on page2.html because the js can't find the div with class wrapper.
I found a similar question here, and a couple comments suggest using localStorage.
I am unfamiliar with localStorage so I tried to do some research, and tried something like this:
On page1.html I inserted this script at the bottom:
<script>
var pageContent = document.querySelector(".page1").innerHTML;
sessionStorage.setItem("page1content", pageContent);
</script>
On page2.html I inserted this script at the bottom:
<script>
document.querySelector(".page2").innerHTML=sessionStorage.getItem("page1content");
</script>
It didn't work for me, but perhaps I used it incorrectly.
I also tried to use cloneNode(), but again, wasn't sure how to transplant the clone of the element onto a new page, only onto the same page I'm cloning from.
Is there another way to accomplish what I'm trying to do?
Obviously this is a very basic example; my actual code will be pumping in much more content from page 1 to page 2, but I just want to get the concept working at least.
The code I had in my example in the description was almost correct, I just had to change sessionStorage to localStorage and it worked.

How to automate selecting certain codes in an html?

Hi I have a question about automating selecting certain content in an HTML. So if we save an webpage as html only, then we'll get HTML codes along with other stylesheets and javascript codes. However, I only want to extract the HTML codes between <div class='post-content' itemprop='articleBody'>and</div> and then create a new HTML file that has the extracted HTML codes. Is there a possible way to do it? Example codes are down below:
<html>
<script src='.....'>
</script>
<style>
...
</style>
<div class='header-outer'>
<div class='header-title'>
<div class='post-content' itemprop='articleBody'>
<p>content we want</p>
</div>
</div></div>
<div class='footer'>
</div>
</html>
While I'm typing, I'm thinking about javascript, which seems to be able to manipulate HTML DOM elements..Is Ruby able to do that? Can I generate a new clean html that only contains content between <div class='post-content' itemprop='articleBody'>and</div> by using javascript or Ruby? However, as for how to write the actual code, I don't have a clue.
So anybody has any idea about it? Thank you so much!
I'm not quite sure what you're asking, but I'll take a crack at it.
Can Ruby modify the DOM on a webpage?
Short answer, no. Browsers don't know how to run Ruby. They do know how to run javascript, so that's what usually used for real-time DOM manipulation.
Can I generate a new clean html
Yes? At the end of the day, HTML is just a specifically formatted string. If you want to download the source from that page and find everything in the <div class='post-content' itemprop='articleBody'> tag, there are a couple of ways to go about that. The best is probably the nokogiri gem, which is a ruby HTML parser. You'll be able to feed it a string (from a file or otherwise) that represents the old page and strip out what you want. Doing that would look something like this:
require 'nokogiri'
page = Nokogiri::HTML(open("https://googleblog.blogspot.com"))
# finds the first child of the <div class="post-content"> element
text = page.css('.post-content')[0].text
I believe that gives you the text you're looking for. More detailed nokogiri instructions can be found here.
You want to use a regular expression. For example:
//The "m" means multi-line
var regEx = /<div class='post-content' itemprop='articleBody'>([\s\S]*?)<\/div>/m;
//The content (you'll put the javascript at the bottom
var bodyCode = document.body.innerHTML;
var match = bodyCode.match( regEx );
//Prints to the console
console.dir( match );
You can see this in action here: https://regex101.com/r/kJ5kW6/1

template insertion in a editor

Describing a scenario:
I am going through the code mentioned below.B asically I am trying to figure out how to program so that
when a user clicks on "Use Template" button , it gets inserted into an editor.
Page 1:
There are lot of templates present
When a user clicks on the "Use Template" button on , it gets inserted into an editor that is present in
the next page (Page 2).
Please find the code snippet below for the first two templates I am going through:
<div id="templatesWrap">
<div class="template" data-templatelocation="templateone" data-templatename="Template ONE" data-templateid="" >
<div class="templateContainer">
<span>
<a href="https://app.abc.com/pqr/core/compose/message/create?token=c1564e8e3cd11bc4t546b587jan31&sMessageTemplateId=templateone&sHubId=&goalComplete=200" title="Use Template">
<img class="thumbnail" src="templatefiles/thumbnail_010.jpg" alt="templateone">
</a>
</span>
<div class="templateName">Template ONE</div>
<p>
Use Template
</p>
</div>
</div>
<div class="template" data-templatelocation="templatetwo" data-templatename="Template TWO" data-templateid="" >
<div class="templateContainer">
<span>
<a href="https://app.abc.com/pqr/core/compose/message/create?token=c1564e8e3cd11bc4t546b587jan31&sMessageTemplateId=templatetwo&sHubId=&goalComplete=200" title="Use Template">
<img class="thumbnail" src="templatefiles/thumbnail_011.jpg" alt="templatetwo">
</a>
</span>
<div class="templateName">Template TWO</div>
<p>
Use Template
</p>
</div>
</div>
And so on ....
How does the link "https://app.abc.com/pqr/core/compose/message/create?token=c1564e8e3cd11bc4t546b587jan31&sMessageTemplateId=templatetwo&sHubId=&goalComplete=200" is inserting the template into the editor which is located on the next page? I haven't understood the token part and lot's of ID's present in the link
which I think are thereason behind inserting the template.
Has anyone come across such link before? Please advise.
Thanks
MORE CLARIFICATIONS:
Thanks for your answer.It did help me somewhat. I have few more questions:
Basically, I am using TinyMCE 4.0.8 version as my editor. The templates, I am using are from here:
https://github.com/mailchimp/email-blueprints/blob/master/templates/2col-1-2-leftsidebar.html
Some questions based on "Tivie" answer.
1) As you can see in the code for "2col-1-2-leftsidebar.html " it's not defined inside <div> tags unlike you defined it in <div> tags. Do you think that I can still
use it using "2col-1-2-leftsidebar.html " name?
2)I believe,for explanation purpose, you have included
`"<div contenteditable="true" id="myEditor">replaced stuff</div>`
and
<button id="btn">Load TPL</button>
<script>
$("#btn").click(function() {
$("#myEditor").load("template.html");
});
</script>
in the same page. Am I right? ( I understand you were trying to make an educated guess here, hence
just asking :) )
In my case, I have a separate page, where I have written code for buttons just like you wrote in editor.html like the following:
<button id="btn">Load TPL</button>. My button is defined inside <div class="templateContainer">.
Also, my templates are defined in a separate folder. So, I will have to grab the content(HTML Template), from
that folder and then insert into TinyMCE 4.08 editor. (Looks like two step process). Could you elaborate
on how should I proceed here?
More Question As of Dec 27
I have modifier my code for the template as follows:
<div class="templateName">Template ONE</div>
<p>
Use Template
</p>
Please note, I have added an additional id attribute for the following purpose.
If I go by the answer mentioned in the Tivia's post, is the following correct?
<script>
$("#temp1").click(function() {
$("#sTextBody").load("FolderURL/template.html");
});
</script>
My editor is defined like the following on Page 2 (Editor Page).
<div class="field">
<textarea id="sTextBody" name="sTextBody" style="width:948px; max-width:948px; height: 70%"></textarea>
</div>
I am confused, like, the script tag I have defined is in Page 1 where I have defined all the template related code
and the Page 2(Editor) page is a different page. It's simply taking me to Editor page (Page 2) and hence not working.
Please advise where I am wrong.
Thanks
MORE QUESTIONS AS of Jan 2
The problem Iam facing is as follows. Basically, for first template , I have the following code.
Code Snippet #1 where "Use "Template" button is present:
<div class="templateName">Template ONE</div>
<p>
Use Template
</p>
And the function suggested in the answer is as follows:
Code Snippet #2 where Editor is present:
<script>
$("#temp1").click(function() {
$("#sTextBody").load("FolderURL/template.html");
});
</script>
Since, I believe I first need to reach to that page after user clicks on "Use Template" button, where the editor is located, I have defined Code Snippet #1 on Page 1 and have defined the Code Snippet #2 and <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> as the very first two script tags in the Page 2 ( Editor Page). But still when I click on "User Template" button on Page 1, it's just letting me to next page and not loading the template into the editor.
Am I doing something wrong here? Please advise.
P.S. The problem I feel is somehow the click function on Page 2 is not getting activated with the temp1 id button mentioned on Page 1.
Thanks
Well, one can only guess without having access to the page itself (and it's source code). I can, however, make an educated guess on how it works.
The URL params follows a pattern. First you have a token that is equal in all templates. This probably means the token does not have any relevance to the template mechanism itself. Maybe it's an authentication token or something. Not relevant though.
Then you have the template identification (templateOne, templateTwo, etc...) followed by a HubId that is empty. Lastly you have a goalComplete=200 which might correspond to the HTTP success code 200 (OK).
Based on this, my guess would be that they are probably using AJAX on the background, to fetch those templates from the server. Then, via JScript, those templates are inserted into the editor box itself.
Using JQuery, something like this is trivial. here's an example:
template.html
<div>
<h1>TEST</h1>
<span>This is a template</span>
</div>
editor.html
<!DOCTYPE HTML>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<div contenteditable="true" id="myEditor">
replaced stuff
</div>
<button id="btn">Load TPL</button>
<script>
$("#btn").click(function() {
$("#myEditor").load("template.html");
});
</script>
</body>
</html>
Edit:
1) Well, since those templates are quite complex and include CSS, you probably want to keep them separated from you editor page (or the template's CSS will mess up your page's css).
However, since you're using TinyMCE, it comes with a template manager built in, so you probably want to use that. Check this link here http://www.tinymce.com/wiki.php/Configuration:templates for documentation.
2) I think 1 answers your question but, just in case, my method above works for any page in any directory, provided it lives on the same domain. Example:
<script>
$("#btn").click(function() {
$("#myEditor").load("someDirectory/template.html");
});
</script>
I recomend you check this page for the specifics on using TinyMCE http://www.tinymce.com/wiki.php/Configuration:templates
EDIT2:
Let me explain the above code:
$("#btn").click(function() { });
This basically tells the browser to run the code inside the brackets when you click the element with an id="btn"
$("#myEditor").load("someDirectory/template.html");
This is an AJAX request (check the documentation here). It grabs the contents of someDirectory/template.html and places them inside the element whose id="myEditor"

Loading HTML dynamically using JavaScript (class.js)

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.

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