Solution to get static script elements after dynamically appended elements - javascript

Within a web application I'm working on, in order to achieve the "app feel" - content being retrieved in the background instead of foreground - I'm using the appendChild() and removeChild() Javascript methods to append and remove elements as necessary. Doing so however, creates a small interference. Like as should be done, I place my script elements right before the closing body tag. But the appendChild() method (obviously as intended) appends child elements at the end, so some of the functions within the (now) above script tags process before its corresponding element even exists in the DOM.
So my question being, what should I do? I was thinking of simply placing a wrapper div inside of the body so I can keep the script tags at the end of the body. But is this the best solution? Is there anything easier, or maybe something to append elements into certain spots within the DOM?

Related

Fire event when browser parses/renders a DOM element

Assume that we know that an element (or a very specific selector) is going to appear on a page. Is it possible to set up beforehand, via JS or jQuery, an event that goes off when the browser gets to that element and parses it? This is NOT content loaded through AJAX but is present in the primary page's source.
The reason for this need is that I'm working with a hosted system that greatly limits where and when I can inject code to fix problems with the page. I can pretty much only place my code at the start and end of what is a really long page. Right now, the page has to load completely before it can inject any desired changes (yuck!). Plus, I cannot make the pages shorter in content.
This is basically the process I would like to happen:
Page begins loading
Listener set up to watch for .specialClass elements
...
.specialClass element gets parsed/added to DOM
Listener triggers function on that element
...
.specialClass element gets parsed/added to DOM
Repeat as before
...
Page finishes rendering
So, is this possible at all? Thanks in advance.

'Persistent' Javascript, like CSS

I have a few javascript functions that changes DOM elements, such as add classes, replace images, etc...
Now, sometimes a page will create a popup or will populate a navigation tree with some extra items without loading a new page. In that case the new element loaded will of course not be affected by my javascript.
For example. Say I give all images an extra class via javascript. Now the page generates a popup with some images in it, and then those images won't be affected by my javascript and the images in the popup won't get said class.
I was wondering if there is a way to make javascript behave like CSS - to be persistent or to work all the time, so that those new images will also be targeted by my scripts?
I hope that id clear :)
Thanks!
EDIT:
I will provide a bit more information here:
Say I have a simeple function like this:
$('.somediv').addClass( '.anotherclass' );
now this function is executed after the page loads.
Is there a way where I can automatically run this function again, when it is detected that a new div of class .somediv has been added to the DOM?
Whenever the new elements are dynamically added to the page you could call a javascript function that resets all the necessary classes and event bindings. Otherwise, if you know on the server-side what classes are necessary for these items you could send them over with the class already assigned to it.

Show an executed script result in a html div tag

I have a button in a simple html file that onClick calls to the next script:
function onShowTest() {
$('div#content').html('<script>alert("Hello")</script>');
};
so basically when I click the button I just get an alert.
What I would actually like to achieve is that in the div tag (content) I will see a result of a script which draws something (not just an alert like in the example which has nothing to do with the result being shown in the div tag).
Also, the function is located in some other file named utils.js.
I tried using jQuery.getScript() but I just can't get it work.
To generate HTML in place, you need to use something like document.write, but that only works at parse time. Once the HTML document is finished, calling it will start a new document and blow away the existing content.
If you want to generate HTML somewhere, then you need to use DOM manipulation to do it, and you can't do it based on where the script element appears.
If you want to draw something then you need to use SVG, Canvas or another API for creating images. SVG is just more DOM manipulation. Canvas would first require DOM manipulation to create a canvas element, and then calling canvas api methods on that element.
If you want the code to do that to come from elsewhere, but get the target from "here", then you should write a function to do the manipulation and pass it an argument which tells it where to perform the manipulation.

how to get the code line number of a dom element?

How can I find the code line number of a specific DOM element?
so I have a DOM element in a JS variable and I need a function that will return the code line number and the filename(path)
this is impossible since you can manipulate the dom.
two reasons:
the browser adds dom elements when parsing the dom (like <tbody> cause most people forget about it)
browsers also have auto correction of unclosed tags etc. etc. so viewing that it is impossible to define wich dom node is in wich line.
you can add / append / manupulate / delete dom nodes using javascript. the dom is not static. as soon as you do something like: var foo = document.createElement("div"); and append it to the body like: document.body.firstChild.appendChild(foo); the line numbers would logicaly change.
you can also move dom nodes around in the tree like changing the parent of an element etc.
you can also create dom nodes without appending them to the tree but you could append them in the later process.
simply said: you cannot figure out in wich line a dom node is unless you have an inspector installed (like rightclick to a node in the visual browser window and select something like "inspect element" in chrome)
every browser does different interpretation of html / dom so its impossible to have the same resulting tree.
the only thing you could do is adding a <script> tag that throws an exception. in most browsers you could then display the current line number through an alert box. (since i think thats "not a good idea" i will not go in details)

Storage and retrieval of DOM element

Wondering if anyone out there has ran into this before....
I'd like to use JavaScript to identify a DOM element on a page, then store it's reference in a database or cookie for later retrieval.
To get specific, what I'm looking to do is create a UI so that when the user CLICKs an element on a page, JavaScript fires the click event, passing the instance of the DOM element clicked on.
easy so far, right?
So what I want to do is store the "identity" of this DOM element, say in a database, so when I later return to this page, I can pull out all stored DOM element identities and get access to them in the page once more.
So this is quite simple if this DOM element has a unique ID. Just store the ID, then when the page comes back up, we just do a getElementByID and we've got our DOM element again.
The problem is that not everything in the DOM has a unique identifier, so there the problem lies.
I had some bad ideas initially, like iterating through the entire DOM and incrementing them with unique class names (dom-01, dom-02, etc) and this would give me an identifier. But this would cause a lot of initial overhead and if the page ever changed, the order of the DOM elements wouldn't be the same, so we wouldn't get back the correct DOM elemet.
I'mve never tried it, but another thought was to serialize the DOM element, stick it in the DB, and then on reload parse to an object, and use that object to find my original DOM element. I've never done that before, so how I can actually compare the restored (parsed) object to the one in the DOM is a big unknown.
Specifics on the serialization solution or any other original ideas for accomplishing this are welcome!!
Thanks in advance everyone!
Here's a jsFiddle solution attempt: http://jsfiddle.net/techbubble/pJgyu/7720/
The approach I took was to compute a simple hash of the HTML content of the target element, or if no such content is present, a hash of the aggregated attributes and values of the element. I have a getElementHash() function that returns a string in the format: TAG:[H | A]:Hash (the H or A indicates if the HTML content or attributes were used to calculate the hash). This produces a unique key for any element on the page that either has HTML content or has at least one attribute (miniscule risk of duplication possible).
For retrieving an element with a previously saved key, I created a getElementByHash() function. It uses the tag that is extracted from the key in a jQuery selector. For each element returned, the HTML content or attributes hash is computed (based on the value "H" or "A" specified in the key) to see if it matches the hash in the key. If there is a match, the search ends and the element is returned.
This approach is impervious to the element being moved around on the page as long as its HTML content (or attributes) remain unchanged. It does not produce a key for elements that have neither any HTML content nor any attributes (which makes them pretty useless anyway).
If you want to keep the location of the node in the DOM, why not just keep an XPath of it? XPath allows you to keep an exact location of a node in a document, as long as that location doesn't change. For instance, you can say something like
//div[#id="xpath_is"]/span[class="cool"]/a[4]
Meaning the 4th <a> tag within a <span class="cool"> within a <div id="xpath_is">
http://www.w3.org/TR/xpath/
http://www.w3schools.com/xpath/default.asp
You can get the XPath of an attribute by Inspecting it with Firebug and right clicking on the node and selecting "Copy XPath". I'm not sure how easy it is to get it from a DOM Node (there are ways, but not sure how many baked implementations there are lying around). It'd be relatively easy to simply look for an ancestor (by traversing upward with .parentNode and building one) and adding .classNames and .ids as you go - but I'm too lazy to write this right now, ;).

Categories