Binding any bootstrap to dynamic HTML - javascript

My question is not about binding a single event to a specific DOM element. My question is, how can you rebind your whole bootstrap library to dynamically generated DOM elements?
For my case I am using the Jquery method .load and I would like to rebind the HTML loaded by that method to my Metro UI bootstrap library. I don't think going to the loaded HTML, checking all the events and components used and re-binding them is an effective solution. I might as well prefer somehow refreshing all bindings after loading the dynamic HTML (if that is also possible). Any help there? Thank you!

After a while of trying I finally found a way to execute the script. I added another method to the callback function to the .load method:
$("#id").load( "dynamic.html", function(){
$.getScript("boostrap.js");
} );
It may not be the most effective way to rebind elements, but at least I make sure all the JS code is re-binded as if the HTML had been loaded from the initial load.

Related

Best way to execute Javascript on an anchor

Generally, there are 3 ways (that I am aware of) to execute javascript from an <a/> tag:
1) Use onclick():
hello
2) Directly link:
hello
3) Or attach externally:
// In an onload event or similar
document.getElementById('hello').onclick = window.alert('Hello');
return false;
<a id="hello" href="#">hello</a>
I am actually loading the link via AJAX, so #3 is basically out. So, is it better to do #1 or #2 or something completely different? Also, why? What are the pitfalls that I should be aware of?
Also of note, the anchor really doesn't link anywhere, hence the href="#", I am using a so the styles conform as this is still an object to be clicked and a button is inappropriate in the context.
Thanks
If you are loading the content via ajax and need to hook up event handlers, then you have these choices:
Put a javascript handler in your HTML with your option 1) or 2). In my mind option 1) is a cleaner way of specifying it, but I don't think there's a mountain of difference between 1) or 2) - they both do essentially the same thing. I'm not a fan of this option in general because I think there's value in keeping the markup and the code separate.
After loading the content with ajax, call some local code that will find and hook up all the links. This would be the same kind of code you would have in your page and execute on DOMReady if the HTML had been static HTML in your page. I would use addEventListener (falling back to attachEvent) to hook up this way as it more cleanly allows multiple listeners for a single object.
Call some code after you load the content with ajax that finds all the links and hooks up the clicks to some generic click handler that can then examine meta data in the link and figure out what should be done on that click based on the meta data. For example, this meta data could be attributes on the clicked link.
When you load the content, also load code that can find each link individually and hook up an appropriate event handler for each link much the way one would do it if the content was just being loaded in a regular page. This would meet the desire of separating HTML from JS as the JS would find each appropriate link and hook up an event handler for it with addEventListener or attachEvent.
Much like jQuery .live() works, hook up a generic event handler for unhandled clicks on links at the document level and dispatch each click based on some meta data in the link.
Run some code that uses an actual framework like jQuery's .live() capability rather than building your own capability.
Which I would use would depend a little on the circumstances.
First of all, of your three options for attaching an event handler, I'd use a new option #4. I'd use addEventListener (falling back to attachEvent for old versions of IE) rather than assigning to onclick because this more cleanly allows for multiple listeners on an item. If it were me, I'd be using a framework (jQuery or YUI) that makes the cross browser compatibility invisible. This allows complete separation of HTML and JS (no JS inline with the HTML) which I think is desirable in any project involving more than one person and just seems cleaner to me..
Then, it's just a question for me for which of the options above I'd use to run the code that hooks up these event listeners.
If there were a lot of different snippets of HTML that I was dynamically loading and it would be cleaner if they were all "standalone" and separately maintainable, then I would want to load both HTML and relevant code at the same time so have the newly loaded code handle hooking up to it's appropriate links.
If a generic standalone system wasn't really required because there were only a few snippets to be loaded and the code to handle them could be pre-included in the page, then I'd probably just make a function call after the HTML snippet was loaded via ajax to have the javascript hook up to the links in the snippet that had just been loaded. This would maintain the complete separation between HTML and JS, but be pretty easy to implement. You could put some sort of key object in each snippet that would identify which piece of JS to call or could be used as a parameter to pass to the JS or the JS could just examine the snippet to see which objects were available and hook up to whichever ones were present.
Number 3 is not "out" if you want to load via AJAX.
var link = document.createElement("a");
//Add attributes (href, text, etc...)
link.onclick = function () { //This has to be a function, not a string
//Handle the click
return false; //to prevent following the link
};
parent.appendChild(link); //Add it to the DOM
Modern browsers support a Content Security Policy or CSP. This is the highest level of web security and strongly recommended if you can apply it because it completely blocks all XSS attacks.
The way that CSP does this is disabling all the vectors where a user could inject Javascript into a page - in your question that is both options 1 and 2 (especially 1).
For this reason best practice is always option 3, as any other option will break if CSP is enabled.
I'm a firm believer of separating javascript from markup. There should be a distinct difference, IMHO, between what is for display purposes and what is for execution purposes. With that said, avoid using onclick attribute and embedding javascript:* in a href attribute.
Alternatives?
You can include javascript library files using AJAX.
You can setup javascript to look for changes in the DOM (i.e. if it's a "standard task", make the anchor use a CSS class name that can be used to bind a specific mechanism when it's later added dynamically. (jQuery does a great job at this with .delegate()))
Run your scripts POST-AJAX call. (Bring in the new content, then use javascript to [re]bind the functionality) e.g.:
function ajaxCallback(content){
// add content to dom
// search within newly added content for elements that need binding
}

JQueryUI: automatically add .accordion(); functionality to any new elements with class="accordion"

I'm using the JQuery-UI Accordion, but I'm trying to find a way to not have to initialize it any time any new element is added. Using AJAX I'm inserting html into a page, but on any page load I am having to re-initialize any accordions-
// .ajax handler
success: function(xml) {
// find accordions
$("div.accordion").accordion();
}
Is there any way I can automatically have this run any time the DOM has changed? I know there is the livequery plugin -- but is there a simpler more elegant method?
Someone may be able to provide more information, but I'm running into a similar situation. As far as I can tell, you have to dynamically apply the accordion based upon the changed DOM. You could just use the .live function and have it run on load. Something like this has worked for me.
$('div.accordion').live('load', accordion());
See if that helps you.
I've ended up going with a different approach and tying functionality to mapped strings. I now use one attribute for everything . I do a find() based upon that and load it with it's associated value.
pseudo: $(this)[$(this).attr('ui:component')]();

Javascript lightbox component that works with arbitrary HTML

Is there a Javascript component that allows me to simply pass it a string made up of arbitrary HTML (any HTML I wish to use) and will show that HTML in a lightbox?
I've been scouring the internet, searching for examples, but it seems like there simply isn't any component capable of doing this.
Even LightWindow, which claims to be all-purpose, still requires me to attach it to an tag with the href set to an element ID.
This isn't what I want. I want to be able to call a function and pass in the HTML myself.
(Another issue with LightWindow is that it requires scriptaculous as a dependency. The project already uses jQuery, and I'd rather not include two frameworks at once.)
Any ideas?
colorbox is great. It relies on JQuery.
To use it with an html string, you would call it like this:
$.colorbox({html:'<p>Hello</p>'});
You can use jqModal or jQuery UI dialog.
SLaks is correct. You should definitly use JQuery UI dialog. Here is an example of using the JQuery dialog as a modal, very similar to using lightbox.
$("#dialog-message").dialog({modal: true});

Simple questions about ajax - Help me understand

I need a little help understanding something. I am using the colorbox plugin to load an external an external html snippet (which works fine). But none of my jquery selectors see the newly loaded html. Is that right (I think it is)? and if so how do I work around that.
Thanks
When you set any properties/bind events in your $(document).ready(function() { ... }) they are executed on page load. So it is all applied to the DOM elements that are present initially.
But when you call the AJAX request and insert some elements into your document, the jquery statements are not executed again (because document.ready doesn't fire). Some solutions to overcome this are:
execute the inside of the document.ready function or the relevant part of it after you insert the new elements.
if the only thing you need are event handlers that should be bound the the new elements you may use live events.

How do you use $.getScript with ajax content?

I am loading an external page that relies heavily on jquery into a div with the $.ajax(); method.
The obvious problem is that the new content needs to be binded to the dom for jquery to work... Everyone talks about just using $.getScript to do this but I can't get it to work. Can some one give me an example and not just a link to the jquery doc page for $.getScript ?
This external page has 6 js files included in it and I need them all binded to the new content as a whole and not per div as in all of the examples I can find.
"new content needs to be binded to the dom for jquery to work"
I assume that you mean that the events binded on elements do not work for the dynamically loaded content. If this is the case, you must bind the elements with live() method. So instead of:
$('#element').click(function() { ... });
Do:
$('#element').live('click', function() { ... });
This way your binds will also affect the loaded content.
If you understood your problem wrong, please let me know.

Categories

Resources