Minimal jQuery template - javascript

I am creating a UI, in which user can add / delete items (of similar layout).
It starts with one item and you can click 'add' to add more. The UI consists of several different types of items.
What I am doing currently is populating a single item item 1 ( of each type ) and on add event, I clone the item 1, replace the changes done by user in item 1 and append the clone to the container.
In simple words, instead of dynamically creating html with jQuery, I am cloning html of a div. But in this approach , I had to change a lot of things to keep to give the new item to initial state.
So, I want to avoid the replacing the edits done by user, so I was thinking something like below,
<script type="text/template" id="item_type1">
<div>
<div>Box</div>
</div>
</script>
<script type="text/template" id="item_type2">
<div>
<div>Box2</div>
</div>
</script>
And on add event, I want to do something like $('#item_type1').html() and $('#item_type2') to create new items.
I know there are sophisticated libraries like handlebar and mustache and underscore has its own way of implementing templates.
But I am not using any of these already and thus do not want to included them just to copy content. I dont want anything special. I am not passing variables. I am just cloning some markup to use again and again.
Is this way to insert html in script tags , going to work in all browsers ? and is it a good way ?
EDIT:
Its for the wp plugin and I assume js is turned on , else the plugin wont work anyways.

What about:
Your HTML should be, for example:
<script type="text/template" id="item_type1">
<div>
<h1>Box1</h1>
<p>
</p>
</div>
</script>
And your code would be:
var templateHtml = $('#item_type1').html();
var $item = $(templateHtml);
$('body').append($item);
$item.on('click', function() {});
This is an easy way that will work on all browsers.

Step 1: Create an HTML file with your template inside of it
Step 2: Using jQuery's load() method, call your HTML template into a div element in the main HTML file:
$("#main-div").load("yourtemplate.html")
Step 3: Be amazed
Is this a good idea? It depends:
If it's a self contained application on a known environment with a determined supported browser and with equally determined settings (like if JavaScript is on or not) then yea, sure. Why not?
If it's open to the public in every single browser possible with many different configurations, then no, it's a horrible idea. If your user doesn't have JavaScript enabled, then your content doesn't show up. Also, if one of your scripts break in production, then you are again left with no content. You can learn this lesson from when Gawker made this same mistake

Related

how to avoid fetching a part of html page which is being called inside another page?

I am calling a .html page(say A.html, which is dynamically created by another software each time a request is made) inside another webpage (say B.html). I am doing this by using the .load() function. Everything works fine but the problem is I donot want the so many "br" tags (empty tags) present at the end of A.html into B.html. Is there any way to avoid fetching those "br" tags into B.html? Any suggestion would be of great help. Thank you in advance.
You can't avoid loading part of a file when you are just accessing it.
The best option would be to simply remove the extra <br> tags from the document to begin with. There is probably a better way to accomplish whatever they are attempting to accomplish.
With some server-side scripting, it could be possible to strip them automatically when you load it, but would probably be pretty bothersome to do.
Instead, if you can't remove the <br> elements for some reason, what might be easier, if you are just dealing with a handful of <br> tags would be to simply strip them out.
Since you mention using the load() function, I'm guessing you are using jQuery.
If that's the case, something like this would cleanly strip out any extra <br> tags from the end of the document.
Here is a JSfiddle which will do it: http://jsfiddle.net/dMJ2F/
var html = "<p>A</p><br><p>B</p><br><p>C</p><br><br /><br/>";
var $html = $('<div>').append(html);
var $br;
while (($br = $html.find('br:last-child')).length > 0) {
$br.remove();
}
$('p').text($html.html());
Basically, throw the loaded stuff in to a div (in memory), then loop through and remove each <br> at the end until there aren't any. You could use regex to do this as well, but it runs a few risks that this jQuery method doesn't.
You shout delete the br-tags in your A.html.
Substitute them by changing the class .sequence with marging-top:30px
And have an other value in your B.html-file.
You also can run this:
$('br', '.sequence').remove();​
in the load-function. It will strip all br-tags.
You can't avoid fetching a part of your page, but you CAN fetch only a part of it.
According to the jQuery docs, you can call load like this:
$("#result").load("urlorpage #form-id");
That way, you only load the form html inside the result element.

How does the example variableInputs for Processing 2.0 javaScript mode works? How to tweak?

I'm using Processing.org looking at the example variableInputs in javaScript mode (can't find it online, but it is included with the download)
It has two tabs, one java and one .js. And a cool example on how to pass data around both.
In the first tab there are some HTML/CSS commented out. Those are building the page when I hit run...
How's that working?
Is it possible to have for instance more than one drop down menu (selector) side by side? I managed to have them, but always one below the another.
Is the way to go to edit the html in the first tab?
help?
do you need me to copy and paste the example here?
[EDIT]
When I hit export, the PDE exports:
index.html
processing.js //(the library it self)
interface.js //(the second tab in the PDE)
sketchName.pde //(the usual pde)
The html tags from above the code are included in index.html, so it can be edited there. Not sure though this is inserted in the html page. So putting the menus side by side turns out to be a HTML question I think... What i also don't know how to do :), but I'll look for it
[edit2] or perhaps a javaScript question... As is interface.js that is making th econtrols... How to control the position of them?
[edit3] well tuns out that the line
<form id="form-form"><!-- empty --></form>
is doing the link, via th id form-form...
Still is it possible to have some menus side by side inatead of one below another?
It is indeed a css/html issue as bfavaretto suggests. In order to do what you asked for try this:
style section in comments (java tab), essentially you have to make the two drop downs' width smaller (45%) and then css hacks to bring them inline, float:left or right
* <style>textarea,input,label,select{display:block;width:95%}select{width:45%;clear:none;float:left}
* input[type=checkbox],input[type=radio]{width: auto}textarea{height:5em},</style>
setController() method, add another ctrl.addMenu(); as such:
element = ctlr.addMenu( "theMenu", menuItems );
element = ctlr.addMenu( "theMenau", menuItems );
The problem after this is that the two labels block the two menus from coming in-line thus you probably have to remove them from these elements and add them manually. In the javascript tab comment out line 157:
//form.appendChild(label);
This line is in function this.addSelection = function ( l, o ) {

What is the simplest way to filter the content of a web page from a drop down menu?

I would like to be able to allow a user to "filter" the contents of an HTML page from a drop down menu.
I have minimal coding skills but maintain a simple website produced using Emacs org-mode. (easy to assemble pages and produce different versions of the same content using tags.) The output is simple HTML.
I can easily produce different versions of a page and make them selectable with a drop down menu to move between them, but this means I have different versions of the same content on my website, which makes retrieval from search engines confusing.
Ideally, I would like user A to be able to select to see the whole page, user B to see some of it, and user C to see most of it except a small portion. This is a convenience to the users (not for security, etc.)
What is the simplest way of implementing this? I realize a web developer would probably use Ajax, etc., but that's not me.
Sounds like you could make use of showing/hiding sections of the page with some DIVs based on a drop down SELECT.
To do this, you wrap the content that you want to filter in some DIVs and create a JavaScript function that "filters" the displayed content based on the value attribute of the SELECT.
Here is a simple example:
HTML
<select id="myDropdown" onchange="filterContent();">
<option value="A">All content</option>
<option value="B">Some content</option>
<option value="C">Little content</option>
</select>
<div id="contentA">
** Content A ***
</div>
<div id="contentB">
** Content B ***
</div>
<div id="contentC">
** Content C ***
</div>
JavaScript
function filterContent() {
var user = document.getElementById("myDropdown").value;
var contentA = document.getElementById("contentA");
var contentB = document.getElementById("contentB");
var contentC = document.getElementById("contentC");
if(user=="A") {
contentA.style.display="block";
contentB.style.display="block";
contentC.style.display="block";
} else if (user=="B") {
contentA.style.display="none";
contentB.style.display="block";
contentC.style.display="block";
} else if (user=="C") {
contentA.style.display="none";
contentB.style.display="none";
contentC.style.display="block";
}
}
Try it here: http://jsfiddle.net/JsZ8S/
Here is another example with multiple different sections that can be shown or hidden based on the selection. Note that the scheme used for IDs is contentA1, contentA2, etc. the letter being the user and the number after the letter is the sequence since IDs must be unique. Also note the difference in the JavaScript code - because we have more sections, we have to account for showing and hiding them in the if/else block: http://jsfiddle.net/JsZ8S/2/
In case you are ready to use jQuery another example is using classes. If you find that you are creating numerous sections and are tired of keeping track of IDs, you might want to use classes. Classes in this case, work like IDs that you can use again and again. You mark any section you want displayed to all users (user A) with class="contentA", any area for users A and B with class="contentB" and everything else just leave unmarked. This is starting to get a bit un-simple at this point but see what you think.
Here is an example (requires jQuery) using classes: http://jsfiddle.net/JsZ8S/5/
You cannot do it with HTML alone. HTML defines a static document with static formatting. You need at least a little bit of JavaScript to dynamically change the page. Otherwise you have to create some sort of link or button that takes the browser to a new page with the desired changes. (This is about how the web worked for the first 5 or so years.)
A small about of JavaScript plus a library like jQuery should make this easy enough to do if you have any programming experience.
HTML is used to just creating the markup and CSS is used to style it. There is no way you can do "filtering" in plain HTML. You will definitely need some JavaScript knowledge. Try your hands on jQuery and angularJS. They are really easy to learn and the documentation is pretty amazing.

How to create interactive tags in html file?

I don't know anything about programming, so I'm trying to find out where to start learning + how difficult my problem is. Since I don't have any programming knowledge, I'll try to describe my problem in natural language, hope that is OK.
I have the html file of the penal code (a type of law). It contains many different rules, that are in numbered paragraphs (§ 1, § 4, etc).
Now I want to look at the source code and manually “tag” the paragraphs according to specific criteria. For example all the paragraphs that concern the use of a weapon get the “weapon” tag, or that have a minimum sentencing of 1 year and higher get a “crime” tag, etc.
At the end I want to view an interactive html file in Firefox/Chrome, where I could for example click on a “crime” button, and all §§§ that were tagged with “crime” would appear in bold red, keeping the rest of the document intact. Ideally I would also be able to click on “weapon” and would only see the §§§ tagged with “weapon”, making the rest of the document disappear.
The function it's just for me, so it would only need to work on a Xubuntu 11.04 desktop with Firefox or Chrome. The original source file would be http://bundesrecht.juris.de/stgb/BJNR001270871.html. The code looks strange to me, is there a way to convert it into something more easily manually editable?
Any help would be greatly appreciated. Primarily I don't know where to start learning. Do I need to know HTML, jQuery, or a programming language like Python? Do I need to set up an Apache server on my PC? Perhaps because of my ignorance of programming, this seems like a not too complex function. Am I mistaken in the belief that an amateur could build something like thins maybe one month?
I think this is not very difficult to make, although the tagging process can be quite labour-intensive.
You don't need much programming skills, especially when you want to tag stuff manually. You probably only need basic HTML and CSS and some Javascript to pull this off.
What I would do is the following
Create a local copy of the HTML file (use Save As in your browser)
Manually tag each § by giving it the appropriate tag as a classname
Create a list of all available tags and let javascript filter out the § you'd like to see
Now Step 1 is pretty easy I guess, so I'll go right to Step 2. The paragraphs in the HTML file are formatted according to a certain pattern, e.g.:
<div class="jnnorm" id="BJNR001270871BJNE009802307" title="Einzelnorm">
<div class="jnheader">
<a name="BJNR001270871BJNE009802307"/>Nichtamtliches Inhaltsverzeichnis
<h3><span class="jnenbez">§ 31</span> <span class="jnentitel">Rücktritt vom Versuch der Beteiligung</span></h3>
</div>
<div class="jnhtml">
<div>
<div class="jurAbsatz">
(1) Nach § 30 wird nicht bestraft, wer freiwillig etc.
</div>
</div>
</div>
</div>
What you want to do now is add your tag to the <div> element with the class jnnorm. So the above example would become (if the tag weapon would be appropriate):
<div class="jnnorm weapon" id="BJNR001270871BJNE009802307" title="Einzelnorm">
You do that for each paragraph in the HTML. This will be pretty boring, but okay.
Now Step 3. First create a list of links of all the tags you've just created. How you create lists in html is explained here. Put this at the top of the HTML document. What you want to do with javascript is when you click on one of the links in your list that only the paragraphs with the given class are shown. This is most easily done with jQuery's click event and the show and hide methods.
Updated with jQuery example
Make a menu like this
<ul id="menu">
<li id="weapon">Weapons</li>
<li id="crime">Crime</li>
</ul>
And then use the following jQuery
<script>
$(document).ready(function(){
// When a <li> element inside an <ul> with the id "menu" is clicked, do the following
$('ul#menu li').click(function(){
// Get the id of the <li> element and append a '.' so we get the right name for the tag (class) we want to show
var tag = '.' + $(this).attr('id');
// Hide all elements of class 'jnnorm'
$('.jnnorm').hide();
// Show all elements with the class name of tag we want
$(tag).show();
});
});
</script>
Note: HTML classes are denoted as .classname in jQuery whereas HTML id's are denoted as #idname.
Good luck!
This could be done using purely HTML/CSS and Javascript, so not server would be needed. JQuery would make the javascript side easier.
Basic idea of how to do it:
Use CSS style classes for your "tags"
Have a button for each tag with an onclick handler that uses JQuery to highlight everything with that tag (or make everything else invisible)
The HTML source code actually looks nicely structured, though it could use a few more linebreaks for sub-paragraphs. Any good HTML/XML editor has an autoformat feature that handles this, though you could get any specific format you want using a programming language with convenient text-manipulation facilities, such as Perl, awk or Python.

Javascript execution order

I want to give a static javascript block of code to a html template designer, which can be:
either inline or external or both
used once or more in the html template
and each block can determine its position in the template relative to the other javascript code blocks.
An example could be image banners served using javascript. I give code to template designer who places it in two places, once for a horizontal banner in the header and once for a vertical banner. The same code runs in both blocks but knowing their positions can determine if to serve a horizontal or a vertical image banner.
Make sense?
Another example: Say you have the same 2 javascript tags in a web page calling an external script on a server. Can the server and/or scripts determine which javascript tag it belongs to?
NOTE: Can we say this is a challenge? I know that I can avoid this puzzle very easily but I come across this on a regular basis.
JavaScript code can locate all <script> elements on the page and it can probably examine the attributes and the content to check from which element it came from. But that's probably not what you want.
What you want is a piece of JavaScript which replaces tags on the page with ad banners. The usual solution is to add a special element, say a IMG, for this and give that IMG an id or a class or maybe even a custom attribute (like adtype="vertical") and then use JavaScript to locate these elements and replace the content by changing the src attribute.
For example, using jQuery, you can should your images like so:
<img src="empty.gif" width="..." height="..." class="ad" adtype="..." />
Then you can locate each image with
$('img.ad')
[EDIT] Well, the server obviously knows which script belongs into which script tag because it inserts the script. So this is a no-brainer.
If the script wants to find out where it is in the DOM, add something which it can use to identify itself, say:
<script>var id= '329573485745';
Then you can walk all script tags and check which one contains the value of the variable id.
If you call an external script, then you can do the same but you must add the ID to the script tag as you emit the HTML:
<script id="329573485745" src="..." />
Then the external script can examine the DOM and lookup the element with this id. You will want to use an UUID for this, btw.
This way, a piece of JS can locate the script tag which added itself to the page.
Best thing would probably be to make an insert once function, and then have him insert only the function call where needed.
Like this:
timescalled=0
function buildad(){
var toinsert="" //Code to generate the desired piece of HTML
document.write(toinsert)
timescalled+=1 //So you can tell how many times the function have been called
}
Now a script block calling the function can simply be inserted wherever a banner is needed
<script type="text/javascript">buildad()</script>
Thanks for the tips everyone but I'll be answering my own question.
I figured out several ways of accomplishing the task and I give you the one which works nicely and is easy to understand.
The following chunk of code relies on outputting dummy divs and jQuery.
<script>
// Unique identifier for all dummy divs
var rnd1="_0xDEFEC8ED_";
// Unique identifier for this dummy div
var rnd2=Math.floor(Math.random()*999999);
// The dummy div
var d="<div class='"+rnd1+" "+rnd2+"'></div>";
// Script which :
// Calculates index of THIS dummy div
// Total dummy divs
// Outputs to dummy div for debugging
var f1="<script>$(document).ready(function(){";
var f2="var i=$('."+rnd1+"').index($('."+rnd2+"'))+1;";
var f3="var t=$('."+rnd1+"').length;";
var f4="$('."+rnd2+"').html(i+' / '+t);";
var f5="});<\/script>";
document.write(d+f1+f2+f3+f4+f5);
</script>
Why not not just place the function call on the page instead of the entire code block? This way you can pass in a parameter to tell it what type of advertisement is needed?
BuildAd('Tower');
BuildAd('Banner');
Javascript itself has no clue of it's position in a page. You have to target a control on the page to get it's location.
I don't think it is possible for JavaScript code to know where it was loaded from. It certainly doesn't run at the point it is found, since execution isn't directly tied to the loading process (code usually runs after the whole DOM is loaded). In fact, in the case of externals, it doesn't even make sense, since only one copy of the code will be loaded no matter how many times it is encountered.
It shouldn't be the same code for each banner - there will be a parameter passed to whatever is serving the image banner which will specify the intended size.
Can you give a specific example of what you need this for?
To edit for your recent example: The simple answer is no. I could help you approach the problem from a different direction if you post details of your problem
The term "static block of code" leaves a lot of room for interpretation.
Inline scripts (e.g., ones that rely on document.write and so must be parsed and executed during the HTML parsing phase) cannot tell where they are in the DOM at runtime. You have to tell them (as in one of the first answers you got).
I think you'll probably find that you need to change your approach.
A common way to keep code and markup separate (which is useful when providing tools to HTML designers who aren't coders) is to have them use a script tag like so:
<script defer async type='text/javascript' src='pagestuff.js'></script>
...which then triggers itself when the page is loaded (using window.onload if necessary, but there are several techniques for being triggered earlier than that, which you want because window.onload doesn't trigger until the images have all loaded).
That script then looks for markers in the markup and manipulates the page accordingly. For instance (this example uses Prototype, but you can do the same with raw JavaScript, jQuery, Closure, etc.):
document.observe("dom:loaded", initPage);
function initPage() {
var verticals = $$('div.vertical');
/* ...do something with the array of "vertical" divs in `verticals`,
such as: */
var index;
for (index = 0; index < verticals.length; ++index) {
vertical.update("I'm vertical #" + index);
}
}
The designers can then have blocks on the page that are filled in by code which they flag up in a way that's normal for them (classes or attributes, etc.). The code figures out what it should do based on the classes/attributes of the blocks it finds when it runs.

Categories

Resources