How do I get the handle to a comment element in javascript? - javascript

I'm working on a side project at work which requires me to write some javascript code. Unfortunately I'm very new to the javascript world and am learning as I go.
So part of what I have to do requires me to find certain comments on the page, and I am using the following line to get all the comments first:
var arr = document.getElementsByTagName("!");
This works perfectly in IE8 and returns an array of all the comments on the page. However this returns an empty array in Google Chrome and I can see an uncaught TypeError (Presumably due to operations being performed on the empty array) when I open up the Developer Console.
Any ideas why this is not working on both browsers? Is this some sort of unsupported operation that I shouldn't be using, or am I just misusing it?
Any help, or pointers in some direction are greatly appreciated! Thank you!
Clarification:
I am doing this in order to manipulate a sharepoint page. That actual intent of this script is to hide a table row that an input element is in. So to do that I need to first find the element, but I can't do that since the attributes for it are basically garbled junk:
<input name="ctl00$m$g_edc51673_bad2_46d5_9a65_e71137e56558$ctl00$ctl04$ctl00$ctl00$ctl‌​00$ctl04$ctl00$ctl00$TextField"
type="text" value="Title" maxlength="255"
id="ctl00_m_g_edc51673_bad2_46d5_9a65_e71137e56558_ctl00_ctl04_ctl00_ctl00_ctl00_‌​ctl04_ctl00_ctl00_TextField"
title="Title" class="ms-long">
(I put in newlines in some places to make it easier to read, but that's all on one line in the source (not that that makes a difference))
So anyway, I can't really use that find the control I'm looking for. And you may say that that has some structure what with the type of the input consistently at the end of the garbage, and the title attribute and all that. But it isn't. Yours truly, Microsoft, does this for some controls, but not for others.
BUT! They are absolutely consistent with providing comments right before this garbled junk that have the name of the element in them, and if I can grab that comment I can foo.parenNode over to what I want.

You can traverse the DOM starting at the node, document and iterating each node's childNodes array. When you find a node, you can test for the nodeType==8
Here are links to
childNodes
nodeType
document.createTextNode
And a small example
<html>
<head>
</head>
<body>
<ul>
<li>junk
<li>text
<!-- comment 1 -->
<li>hi
<li>hello
<li>world
</ul>
<br/>
<!-- comment 2 -->
<script>
window.onload=findcommentsstart
var msgs = [];
function findcommentsstart()
{
findcomments(document);
var txt = document.createTextNode(msgs.join("\n"));
document.getElementsByTagName("body")[0].appendChild(txt);
}
function findcomments(d)
{
if(!d)
return;
if(d.nodeType==8)
msgs.push("found a comment node " + d.data);
if(!d.childNodes)
return;
for(var i=0;i<d.childNodes.length;i++)
findcomments(d.childNodes[i]);
}
</script>
</body>
</html>

You could avoid this by loading the page in a String variable (e.g. using AJAX) and parsing it.
I would say ignoring comments should be the desired behaviour, beacuse comments should be considered a "no-go" for the parser/interpreter.
IE is always doing some fancy (non-standard) stuff which often breaks things ;)

Related

Strip HTML elements within DIV

I have a simple search engine on one of our older websites. This site is running IIS 6.0 on Windows Server 2003. The search functionality is provided by Microsoft Indexing Service.
You can see the search functionality on our website. (Just type in "speakers" and you will see some hits.
I would like to use the "FullHit" feature offered by the indexing service. When using this feature the Indexing service inserts the full hit results in between "begindetail" and "enddetail" on a target web page.
The problem that I have is that the documents that are being returned have HTML. This looks messy. (Just click on "Hit Locator Tool" in the search results above to see what I mean.)
I would like to create a DIV section such as ...
<DIV name="target">
begindetail
enddetail
</DIV>
Then, after the page is populated I would like to use javascript to strip out all of the HTML elements (but not the data) between the opening and closing DIV.
For example, <FONT color="magenta">Good Data</FONT> would be modified to only show Good Data.
I can also use Classic ASP if necessary.
Please let me know if you have any suggestions or know of any functions that I can add to the target page to accomplish this task.
Thanks in advance.
I inspected your webpage, and there definitely must be some logic errors in your ASP code. (1) Instead of something like <div></div> being passed to the browser, it is HTML entities for special characters, so it is being passed like &ltDIV&gt &lt/DIV&gt, which is very ugly and is why it is rendering as text instead of HTML code. In your ASP code, you must not be parsing the search result text before passing it to the browser. (2) All of this improperly-formatted code is inserted after the first closing html tag, and then there are closing body and html tags after the improperly-formatted code, so somewhere in your ASP code, you are telling it to append the code to the end of the document, rather than insert it inside the original <body></body>.
If you want to decode the mixture of HTML entities, <br> tags, and text into rendered HTML, this JavaScript may work:
window.onload = function() {
var text = decodeHTMLEntities(document.body.innerText);
document.write(text);
}
function decodeHTMLEntities(text) {
var entities = [
['amp', '&'],
['apos', '\''],
['#x27', '\''],
['#x2F', '/'],
['#39', '\''],
['#47', '/'],
['lt', '<'],
['gt', '>'],
['nbsp', ' '],
['quot', '"']
];
for (var i = 0, max = entities.length; i < max; ++i)
text = text.replace(new RegExp('&'+entities[i][0]+';', 'g'), entities[i][1]);
return text;
}
jsFiddle: https://jsfiddle.net/6ohc1tkr/
But first things first, you need to fix your ASP code, or whatever you use to parse and then display the search results. That's what is causing the improper formatting and display of the HTML. Show us your back-end code and then we can help you.
This is what I used to accomplish what you are trying to do.
string-strip-html
It worked pretty well for me.
I now have the search feature working as expected. I would like to thank everyone for their insightful comments. This feedback helped me identify and fix the problem.
OS: Windows Server 2003
IIS: 6.0
Microsoft Index Server
The hit locator tool will only work properly for HTML pages. If you use this tool with a simple TXT file then the results will not be displayed correctly.

Why does firstChild not return the first element?

I was writing some code the other day, and for some reason, I had no idea why this happened, but this was part of the code that I had written.
var item = document.getElementByClass('object');
var innerImageId = item.firstChild.id;
I went over this code a lot of times. The problem of this code is that the value of innerImageId is undefined. The firstChild of item is an image. I need to get the id of the image, but no matter how many times I went over the code, it did not work. Here is the HTML file of the code.
<div class="object inventory-box">
<img src="image.png" id="sample-image">
</div>
Doesn't this seem correct? Well, I did some debugging in Google Chrome, and it turns out that there are 3 nodes in the div "object". The id of the first and the last node was undefined, but the 2nd one was "sample-image".
I then tried "firstElementChild" instead of "firstChild", and this worked well.
Then just to test it out, I did something like this-
<div class="object inventory-box">
<img src="image.png" id="sample-image">
</div>
(or with multiple lines of unnecessary whitespace)
but it still shows 3 nodes, the enter symbol, the div, and another enter symbol.
This problem keeps occurring in Chrome, Internet Explorer and Firefox.
Can someone please explain why there are these random 2 extra nodes?
The browser insert a text node when there are white spaces or new lines in your code. You are targeting one of those.
Try
var img = document.querySelector('.object img');
var innerImageId = img.id;
You can also use firstElementChild in place of firstChild which will skip those empty text nodes.
EDIT: Blah thanks BAM5 just not paying attention as I typed.
There isn't a getElementByClass method, this is why you failed. Open console and you'll see JS error. I guess what you thought were getElementsByClassName. Note it's in plural form, and it returns an array-like.
Even if you get over the first issue, you may still fail due to your markup. firstChild does return the first one among children, including the text nodes. Your better choice is firstElementChild. Or you have to write like this to avoid text node children:
<div><img></div>
So, this should give what you wanted:
var items = document.getElementsByClassName('object');
var innerImageId = items[0].firstElementChild.id;
On the other hand, other answers pointed that querySelector can do the job, indeed. And it has a brother querySelectorAll. You could search MDN for their usages and slight difference in between.
Use firstElementChild instead of firstChild. As l. Catallo said, you may be getting a text node instead of an element.
Looks like Atheist beat me to it, but in his answer he incorrectly used firstChildElement. Would comment, but not enough rep...
I faced a similar question while I was learning DOM exploration and I observed that, when there is a space or the next tag is on the next line, the node list normally shows a text node. For Example:
If I wrote my HTML code as below, and tried to get all the child nodes of the element body.
HTML Code:
<body>
<h2> Lets Study DOM!! </h2>
<input type = 'text' id = 'topic'> </input></br>
<button onClick = addToList()> Click Me to Add </button>
Javascript:
console.log(document.querySelector('body').childNodes);
The above code gave me the following output:
[text, h2, text, input#topic, text, br, text, button, text, ul#unordered, text, script]
On the other hand, if I modified my code as shown below, and then tried to print the node list, I got a different output as shown below:
HTML Code:
<body><h2> Lets Study DOM!! </h2>
<input type = 'text' id = 'topic'> </input></br>
<button onClick = addToList()> Click Me to Add </button>
Javascript:
console.log(document.querySelector('body').childNodes);
The above code gave me the following output:
[h2, text, input#topic, text, br, text, button, text, ul#unordered, text, script]
So clearly, the browser considers the space after the body tag as a text node.

Should I work with strings or nodes when generating content in Javascript?

I'm trying to set up pages as templates for an application that eventually needs to work offline.
Right now I'm playing around with snippets of HTML code (= enhanced but unformatted jquery mobile elements), which I'm storing as HTML pages like so:
<!-- template_listview.html -->
<!DOCTYPE html>
<html>
<head><title>static_listview_templates</title></head>
<body>
<!-- listview basic start -->
<ul id="tmp_listview_basic" class="ui-listview"></ul>
<!-- listview basic end -->
<!-- listview inset start -->
<ul id="tmp_listview_inset" class="ui-listview ui-listview-inset ui-corner-all ui-shadow"></ul>
<!-- listview inset end -->
</bdoy>
</html>
My application uses requireJS, so the first time the user hits a page that contains a listview (with a data-config attribute specifying dynamic content to load as well as listview appearance), require pulls the above template, which will be cached for all subsequent uses.
Right now the page above is returned as HTML string. As it will include all "variations" of listview elements (<ul>,<ol>,<li>...), I need some means of selecting the element I need on the specific occasion, which is where I'm stuck right now.
Question:
In terms of performance, is it better to work with a big string of the returned HTML template and try to extract the necessary substrings or should I instead wrap this into $() and use jquery/javascript to pull what I need?
If it should be a string, is there an easy way to pull an element (from to) from this string?
Thanks!
I'd assume string abstraction would be better performance-wise.
In fact, if I am right in thinking that you want to get the relevant listviews from the result as a string then according to the following jsperf test I wrote, string abstraction is much quicker:
http://jsperf.com/jqobj-vs-string-abstraction
Therefore, you can use the string abstraction method I wrote for that test to get your listviews from the result:
function getTemplateBlock(block, context) {
var regex = new RegExp('<!-- ' + block + '(.)+' + block + '(.)+?-->'),
tmpl = context.match(regex);
return tmpl.length ? tmpl[0].replace(/<!--[\s\S]*?-->/g, '') : '';
}
// get listview templates where 'mystuff' is
// the HTML string returned by your request
var basic = getTemplateBlock('listview basic', mystuff),
inset = getTemplateBlock('listview inset', mystuff);
Also, the answer to your question on how to select from your created object is in that jsperf too...
$('<div />').html(mystuff).find('ul');
This is necessary because .find() searches the descendants of the matched elements so if we make the matched element a new <div /> and append our result, we can search the <div /> for our <ul />'s.
Taken from the jQuery docs:
"Given a jQuery object that represents a set of DOM elements, the .find() method allows us to search through the descendants of these elements in the DOM tree and construct a new jQuery object from the matching elements."
Use $(html). It does pretty much exactly what you need. It's an in-memory operation. If you aren't planning to try to do hundreds of these a second, you'll get more bang for you buck focusing your performance optimization efforts on other areas as indicated by performance analysis tools like yslow or similar.

Javascript error: [elementname] has no properties

I'm doing some maintenance coding on a webapp and I am getting a javascript error of the form: "[elementname] has no properties"
Part of the code is being generated on the fly with an AJAX call that changes innerHTML for part of the page, after this is finished I need to copy a piece of data from a hidden input field to a visible input field.
So we have the destination field: <input id="dest" name="dest" value="0">
And the source field: <input id="source" name="source" value="1">
Now when the ajax runs it overwrites the innerHTML of the div that source is in, so the source field now reads: <input id="source" name="source" value="2">
Ok after the javascript line that copies the ajax data to innerHTML the next line is:
document.getElementById('dest').value = document.getElementById('source').value;
I get the following error: Error: document.getElementById("source") has no properties
(I also tried document.formname.source and document.formname.dest and same problem)
What am I missing?
Note1: The page is fully loaded and the element exists. The ajax call only happens after a user action and replaces the html section that the element is in.
Note2: As for not using innerHTML, this is how the codebase was given to me, and in order to remove it I would need to rewrite all the ajax calls, which is not in the scope of the current maintenance cycle.
Note3: the innerHTML is updated with the new data, a whole table with data and formatting is being copied, I am trying to add a boolean to the end of this big chunk, instead of creating a whole new ajax call for one boolean. It looks like that is what I will have to do... as my hack on the end then copy method is not working.
Extra pair of eyes FTW.
Yeah I had a couple guys take a look here at work and they found my simple typing mistake... I swear I had those right to begin with, but hey we live and learn...
Thanks for the help guys.
"[elementname] has no properties" is javascript error speak for "the element you tried to reference doesn't exist or is nil"
This means you've got one or more of a few possible problems:
Your page hasn't rendered yet and you're trying to reference it before it exists
You've got a spelling error
You've named your id the same as a reserved word (submit on a submit button for instance)
What you think you're referencing you're really not (a passed variable that isn't what you think you're passing)
Make sure your code runs AFTER the page fully loads. If your code runs before the element you are looking for is rendered, this type of error will occur.
What your describing is this functionality:
<div id="test2">
<input id="source" value="0" />
</div>
<input id="dest" value="1" />
<script type="text/javascript" charset="utf-8">
//<![CDATA[
function pageLoad()
{
var container = document.getElementById('test2');
container.innerHTML = "<input id='source' value='2' />";
var source = document.getElementById('source');
var dest = document.getElementById('dest');
dest.value = source.value;
}
//]]>
</script>
This works in common browsers (I checked in IE, Firefox and Safari); are you using some other browser or are you sure that it created the elements correct on innerHTML action?
It sounds like the DOM isn't being updated with the new elements to me.
For that matter, why are you rewriting the entire div just to change the source input? Wouldn't it be just as easy to change source's value directly?
This is a stretch, but just may be the trick - I have seen this before and this hack actually worked.
So, you said:
Ok after the javascript line that copies the ajax data to innerHTML the next line is:
document.getElementById('dest').value = document.getElementById('source').value;
Change that line to this:
setTimeout(function() {
document.getElementById("dest").value = document.getElementById("source").value;
}, 10);
You really shouldn't need this, but it is possible that the time between your setting the innerHTML and then trying to access the "source" element is so fast that the browser is unable to find it. I know, sounds completely whack, but I have seen browsers do this in certain instances for some reason that is beyond me.
Generally you shouldn't use innerHTML, but create elements using DOM-methods. I cannot say if this is your problem.

How to store arbitrary data for some HTML tags

I'm making a page which has some interaction provided by javascript. Just as an example: links which send an AJAX request to get the content of articles and then display that data in a div. Obviously in this example, I need each link to store an extra bit of information: the id of the article. The way I've been handling it in case was to put that information in the href link this:
<a class="article" href="#5">
I then use jQuery to find the a.article elements and attach the appropriate event handler. (don't get too hung up on the usability or semantics here, it's just an example)
Anyway, this method works, but it smells a bit, and isn't extensible at all (what happens if the click function has more than one parameter? what if some of those parameters are optional?)
The immediately obvious answer was to use attributes on the element. I mean, that's what they're for, right? (Kind of).
<a articleid="5" href="link/for/non-js-users.html">
In my recent question I asked if this method was valid, and it turns out that short of defining my own DTD (I don't), then no, it's not valid or reliable. A common response was to put the data into the class attribute (though that might have been because of my poorly-chosen example), but to me, this smells even more. Yes it's technically valid, but it's not a great solution.
Another method I'd used in the past was to actually generate some JS and insert it into the page in a <script> tag, creating a struct which would associate with the object.
var myData = {
link0 : {
articleId : 5,
target : '#showMessage'
// etc...
},
link1 : {
articleId : 13
}
};
<a href="..." id="link0">
But this can be a real pain in butt to maintain and is generally just very messy.
So, to get to the question, how do you store arbitrary pieces of information for HTML tags?
Which version of HTML are you using?
In HTML 5, it is totally valid to have custom attributes prefixed with data-, e.g.
<div data-internalid="1337"></div>
In XHTML, this is not really valid. If you are in XHTML 1.1 mode, the browser will probably complain about it, but in 1.0 mode, most browsers will just silently ignore it.
If I were you, I would follow the script based approach. You could make it automatically generated on server side so that it's not a pain in the back to maintain.
If you are using jQuery already then you should leverage the "data" method which is the recommended method for storing arbitrary data on a dom element with jQuery.
To store something:
$('#myElId').data('nameYourData', { foo: 'bar' });
To retrieve data:
var myData = $('#myElId').data('nameYourData');
That is all that there is to it but take a look at the jQuery documentation for more info/examples.
Just another way, I personally wouldn't use this but it works (assure your JSON is valid because eval() is dangerous).
<a class="article" href="link/for/non-js-users.html">
<span style="display: none;">{"id": 1, "title":"Something"}</span>
Text of Link
</a>
// javascript
var article = document.getElementsByClassName("article")[0];
var data = eval(article.childNodes[0].innerHTML);
Arbitrary attributes are not valid, but are perfectly reliable in modern browsers. If you are setting the properties via javascript, than you don't have to worry about validation as well.
An alternative is to set attributes in javascript. jQuery has a nice utility method just for that purpose, or you can roll your own.
A hack that's going to work with pretty much every possible browser is to use open classes like this: <a class='data\_articleid\_5' href="link/for/non-js-users.html>;
This is not all that elegant to the purists, but it's universally supported, standard-compliant, and very easy to manipulate. It really seems like the best possible method. If you serialize, modify, copy your tags, or do pretty much anything else, data will stay attached, copied etc.
The only problem is that you cannot store non-serializable objects that way, and there might be limits if you put something really huge there.
A second way is to use fake attributes like: <a articleid='5' href="link/for/non-js-users.html">
This is more elegant, but breaks standard, and I'm not 100% sure about support. Many browsers support it fully, I think IE6 supports JS access for it but not CSS selectors (which doesn't really matter here), maybe some browsers will be completely confused, you need to check it.
Doing funny things like serializing and deserializing would be even more dangerous.
Using ids to pure JS hash mostly works, except when you try to copy your tags. If you have tag <a href="..." id="link0">, copy it via standard JS methods, and then try to modify data attached to just one copy, the other copy will be modified.
It's not a problem if you don't copy tags, or use read only data. If you copy tags and they're modified you'll need to handle that manually.
Using jquery,
to store: $('#element_id').data('extra_tag', 'extra_info');
to retrieve: $('#element_id').data('extra_tag');
I know that you're currently using jQuery, but what if you defined the onclick handler inline. Then you could do:
<a href='/link/for/non-js-users.htm' onclick='loadContent(5);return false;'>
Article 5</a>
You could use hidden input tags. I get no validation errors at w3.org with this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang='en' xml:lang='en' xmlns='http://www.w3.org/1999/xhtml'>
<head>
<meta content="text/html;charset=UTF-8" http-equiv="content-type" />
<title>Hello</title>
</head>
<body>
<div>
<a class="article" href="link/for/non-js-users.html">
<input style="display: none" name="articleid" type="hidden" value="5" />
</a>
</div>
</body>
</html>
With jQuery you'd get the article ID with something like (not tested):
$('.article input[name=articleid]').val();
But I'd recommend HTML5 if that is an option.
Why not make use of the meaningful data already there, instead of adding arbitrary data?
i.e. use <a href="/articles/5/page-title" class="article-link">, and then you can programmatically get all article links on the page (via the classname) and the article ID (matching the regex /articles\/(\d+)/ against this.href).
As a jQuery user I would use the Metadata plugin. The HTML looks clean, it validates, and you can embed anything that can be described using JSON notation.
This is good advice. Thanks to #Prestaul
If you are using jQuery already then you should leverage the "data"
method which is the recommended method for storing arbitrary data on a
dom element with jQuery.
Very true, but what if you want to store arbitrary data in plain-old HTML? Here's yet another alternative...
<input type="hidden" name="whatever" value="foobar"/>
Put your data in the name and value attributes of a hidden input element. This might be useful if the server is generating HTML (i.e. a PHP script or whatever), and your JavaScript code is going to use this information later.
Admittedly, not the cleanest, but it's an alternative. It's compatible with all
browsers and is valid XHTML. You should NOT use custom attributes, nor should you really use attributes with the 'data-' prefix, as it might not work on all browsers. And, in addition, your document will not pass W3C validation.
As long as you're actual work is done serverside, why would you need custom information in the html tags in the output anyway? all you need to know back on the server is an index into whatever kind of list of structures with your custom info. I think you're looking to store the information in the wrong place.
I will recognize, however unfortunate, that in lots of cases the right solution isn't the right solution. In which case I would strongly suggest generating some javascript to hold the extra information.
Many years later:
This question was posted roughly three years before data-... attributes became a valid option with the advent of html 5 so the truth has shifted and the original answer I gave is no longer relevant. Now I'd suggest to use data attributes instead.
<a data-articleId="5" href="link/for/non-js-users.html">
<script>
let anchors = document.getElementsByTagName('a');
for (let anchor of anchors) {
let articleId = anchor.dataset.articleId;
}
</script>
I advocate use of the "rel" attribute. The XHTML validates, the attribute itself is rarely used, and the data is efficiently retrieved.
So there should be four choices to do so:
Put the data in the id attribute.
Put the data in the arbitrary attribute
Put the data in class attribute
Put your data in another tag
http://www.shanison.com/?p=321
You could use the data- prefix of your own made attribute of a random element (<span data-randomname="Data goes here..."></span>), but this is only valid in HTML5. Thus browsers may complain about validity.
You could also use a <span style="display: none;">Data goes here...</span> tag. But this way you can not use the attribute functions, and if css and js is turned off, this is not really a neat solution either.
But what I personally prefer is the following:
<input type="hidden" title="Your key..." value="Your value..." />
The input will in all cases be hidden, the attributes are completely valid, and it will not get sent if it is within a <form> tag, since it has not got any name, right?
Above all, the attributes are really easy to remember and the code looks nice and easy to understand. You could even put an ID-attribute in it, so you can easily access it with JavaScript as well, and access the key-value pair with input.title; input.value.
One possibility might be:
Create a new div to hold all the extended/arbitrary data
Do something to ensure that this div is invisible (e.g. CSS plus a class attribute of the div)
Put the extended/arbitrary data within [X]HTML tags (e.g. as text within cells of a table, or anything else you might like) within this invisible div
Another approach can be to store a key:value pair as a simple class using the following syntax :
<div id="my_div" class="foo:'bar'">...</div>
This is valid and can easily be retrieved with jQuery selectors or a custom made function.
In html, we can store custom attributes with the prefix 'data-' before the attribute name like
<p data-animal='dog'>This animal is a dog.</p>.
Check documentation
We can use this property to dynamically set and get attributes using jQuery like:
If we have a p tag like
<p id='animal'>This animal is a dog.</p>
Then to create an attribute called 'breed' for the above tag, we can write:
$('#animal').attr('data-breed', 'pug');
To retrieve the data anytime, we can write:
var breedtype = $('#animal').data('breed');
At my previous employer, we used custom HTML tags all the time to hold info about the form elements. The catch: We knew that the user was forced to use IE.
It didn't work well for FireFox at the time. I don't know if FireFox has changed this or not, but be aware that adding your own attributes to HTML elements may or may-not be supported by your reader's browser.
If you can control which browser your reader is using (i.e. an internal web applet for a corporation), then by all means, try it. What can it hurt, right?
This is how I do you ajax pages... its a pretty easy method...
function ajax_urls() {
var objApps= ['ads','user'];
$("a.ajx").each(function(){
var url = $(this).attr('href');
for ( var i=0;i< objApps.length;i++ ) {
if (url.indexOf("/"+objApps[i]+"/")>-1) {
$(this).attr("href",url.replace("/"+objApps[i]+"/","/"+objApps[i]+"/#p="));
}
}
});
}
How this works is it basically looks at all URLs that have the class 'ajx' and it replaces a keyword and adds the # sign... so if js is turned off then the urls would act as they normally do... all "apps" (each section of the site) has its own keyword... so all i need to do is add to the js array above to add more pages...
So for example my current settings are set to:
var objApps= ['ads','user'];
So if i have a url such as:
www.domain.com/ads/3923/bla/dada/bla
the js script would replace the /ads/ part so my URL would end up being
www.domain.com/ads/#p=3923/bla/dada/bla
Then I use jquery bbq plugin to load the page accordingly...
http://benalman.com/projects/jquery-bbq-plugin/
I have found the metadata plugin to be an excellent solution to the problem of storing arbitrary data with the html tag in a way that makes it easy to retrieve and use with jQuery.
Important: The actual file you include is is only 5 kb and not 37 kb (which is the size of the complete download package)
Here is an example of it being used to store values I use when generating a google analytics tracking event (note: data.label and data.value happen to be optional params)
$(function () {
$.each($(".ga-event"), function (index, value) {
$(value).click(function () {
var data = $(value).metadata();
if (data.label && data.value) {
_gaq.push(['_trackEvent', data.category, data.action, data.label, data.value]);
} else if (data.label) {
_gaq.push(['_trackEvent', data.category, data.action, data.label]);
} else {
_gaq.push(['_trackEvent', data.category, data.action]);
}
});
});
});
<input class="ga-event {category:'button', action:'click', label:'test', value:99}" type="button" value="Test"/>
My answer might not apply to your case. I needed to store a 2D table in HTML, and i needed to do with fewest possible keystrokes. Here's my data in HTML:
<span hidden id="my-data">
IMG,,LINK,,CAPTION
mypic.jpg,,khangssite.com,,Khang Le
funnypic.jpg,,samssite.com,,Smith, Sam
sadpic.png,,joyssite.com,,Joy Jones
sue.jpg,,suessite.com,,Sue Sneed
dog.jpg,,dogssite.com,,Brown Dog
cat.jpg,,catssite.com,,Black Cat
</span>
Explanation
It's hidden using hidden attribute. No CSS needed.
This is processed by Javascript. I use two split statements, first on newline, then on double-comma delimiter. That puts the whole thing into a 2D array.
I wanted to minimize typing. I didn't want to redundantly retype the fieldnames on every row (json/jso style), so i just put the fieldnames on the first row. That a visual key for the programmer, and also used by Javascript to know the fieldnames. I eliminated all braces, brackets, equals, parens, etc. End-of-line is record delimiter.
I use double-commas as delimiters. I figured no one would normally use double-commas for anything, and they're easy to type. Beware, programmer must enter a space for any empty cells, to prevent unintended double-commas. The programmer can easily use a different delimiter if they prefer, as long as they update the Javascript. You can use single-commas if you're sure there will be no embedded commas within a cell.
It's a span to ensure it takes up no room on the page.
Here's the Javascript:
// pull 2D text-data into array
let sRawData = document.querySelector("#my-data").innerHTML.trim();
// get headers from first row of data and load to array. Trim and split.
const headersEnd = sRawData.indexOf("\n");
const headers = sRawData.slice(0, headersEnd).trim().split(",,");
// load remaining rows to array. Trim and split.
const aRows = sRawData.slice(headersEnd).trim().split("\n");
// trim and split columns
const data = aRows.map((element) => {
return element.trim().split(",,");
});
Explanation:
JS uses lots of trims to get rid of any extra whitespace.

Categories

Resources