jQuery UI dialog display inside frame, from bookmarklet? - jquery-ui

I'm writing a bookmarklet which needs to work in the context of pages whose design I don't control. Some of the pages I need the bookmarklet to function in use frames (in framesets). Is it possible for a jQuery-UI dialog to work inside a frame?
Currently, when I encounter a page with a frameset, I creating my dialog like this:
var frame = window.frames[0];
var div = $(frame.document.createElement("div"));
div.html("My popup contents");
div.dialog( ... );
The result is that jQuery appends the ui-widget div to the main document, rather than the frame's document. Since the main document is just a frameset, nothing is displayed. I can't find any options in the jquery-ui API to specify which document the widgets should be constructed in. The bookmarklet will necessarily be running (or at least starting) from within the context of the outer document.
I'm aware that it won't be possible to display an overlay over the frames; I'm comfortable with display just in a single frame. Also, some other notable bookmarklets fail to function on pages with framesets, so this may be a common problem.
Suggestions?

Bookmarklets typically don't use jQuery. Most bookmarklets open a window which has jQuery.

Here's what I ended up doing: rather than attempting to display within or over a frame, I just had the bookmarklet rewrite the page to remove the framesets and add my own body and content to the page. This allows the bookmarklet to still introspect the frames and get data that it needs from them to construct the overlay prior to removing the framesets, but allows the overlay to still work.
Something like this:
if (window.frames) {
for (var i = 0; i < window.frames.length; i++) {
// ... grab data from the frame ...
}
}
if ($("frameset")) {
$("html").children("frameset").remove();
document.body = document.createElement("body");
$("html").append(document.body);
// ... add my stuff to body ...
}

Related

jquery mobile trigger('create') callback function

I am using jquery mobile and using the $().trigger('create') function to initiate it. I need a callback after this function is done modifying the html with the new styling. Is this possible?
I need this because i need the new dimensions of the screen after an ajax load of new content.
I would use TriggerHandler(). You can bind to your custom event...
See the DEMO at the bottom of the link:
http://api.jquery.com/triggerHandler/
I found that the "updatelayout" event gets fired when I do a x$.trigger("create"). This from some js using Backbone...
var content$ = this.$el.find("#somediv");
content$.on('updatelayout', function () { alert("woo hoo"); });
content$.trigger("create"); // add some JQM magic, wait for the 'woo hoo'
From the jQuery api:
"This event is triggered by components within the framework that dynamically show/hide content, and is meant as a generic mechanism to notify other components that they may need to update their size or position."
It turns out that there is a devil in the detail. Not all triggered JQM content leads to a JQ "updatelayout" event. I had to add a wrapper div with 'data-role="controlgroup" in another case to get it to fire. More digging required...

JQM - Inject dynamic content at load time only

I'm trying to dynamically populate a select tag at load time (latest jQM version) using a custom template filling function.
If the fn is called in the "pagebeforechange" event, the select tag is properly initialized. Since this event is called on every page transition, I thought of moving the fn to the 'pageinit' event. This does not work, presumably because the DOM is not yet fully available. How can I coerce jQM to inject content in a page only once? Currently, I am using a kludge. There surely must be a smarter way. Thanks for any suggestions.
$(document).bind('pageinit', function () {
InitSelTagTest("#selActTag", "tplTag"); // Does not work.
});
$(document).bind("pagebeforechange", function (e, data) {
if ($("#selActTag").children().size() === 0) {
InitSelTagTest("#selActTag", "tplTag"); // Kludge, but it works
}
});
function InitSelTagTest(el,tpl) { // Append all tags to element el
var lstAllTags = JSON.parse($("#hidTag").val()); // Create tag array
// Retrieve html content from template.
var cbeg = "//<![" + "CDATA[", cend = "//]" + "]>";
var rslt = tmpl(tpl, { ddd: lstAllTags }).replace(cbeg, ").replace(cend,");
$(el).html(rslt).trigger("create"); // Add to DOM.
}
EDIT
In response to Shenaniganz' comment, it seems that the "pagebeforecreate" event could do the trick ie.
$("#pgAct").live("pagebeforecreate", function () {
// Populate tag select. Works. Traversed only once.
InitSelTag("#selActTag", "tplTag");
});
I'm not sure I fully understand your question but I'll throw a few things out there and you let me know if I can extend further.
To make something trigger only once on page load you can try to implement a regular JQuery $(document).ready(function(){}) aka $(function(){}) for the exact reason why JQuery Mobile users are told not to use it. It triggers only once on DOM load. Further pages don't trigger it because they're being switched via Ajax.
Other than that, on regular dynamic content loading you take a look at the following example I put together for someone else earlier:
http://jsbin.com/ozejif/1/edit

How to overlay xul with no id?

I'm writing a firefox addon and I'm trying to use an xul overlay to insert a canvas element. The problem is, the parent xul node of where I want to insert the canvas element has no id. Is it possible to do if there's no id? I also tried using the anonid for elements that had no id as you can see below, but had no luck with that either.
My xul overlay:
<?xml version="1.0"?>
<overlay id="myOverlay"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
xmlns:html="http://www.w3.org/1999/xhtml">
<tabbrowser id="content">
<tabbox anonid="tabbox">
<tabpanels anonid="panelcontainer">
<notificationbox>
<stack anonid="browserStack">
<html:canvas id="myCanvas" height="100%" />
</stack>
</notificationbox>
</tabpanels>
</tabbox>
</tabbrowser>
</overlay>
I would like the canvas element to be inserted after each browser element in each tab like this: http://img.photobucket.com/albums/v215/thegooddale/80eae9ee.jpg
There are multiple issues with the attempt to use overlays for this:
Overlays don't work without an ID, they simply don't have another way to address an element.
Overlays cannot apply to something that isn't there when the window loads - they are a one-time thing and cannot consider dynamic elements that are created later.
Overlays cannot apply to anonymous elements (displayed in red in DOM Inspector). These elements are injected by an XBL binding and are not part of the XUL document.
You will have to use JavaScript and inject your canvas "manually" each time. You can use the TabOpen event to get notified whenever a tab is opened. Something like this should work (untested code):
// Always wait for the window to initialize first
window.addEventListener("load", function()
{
function initTab(tab)
{
var browser = window.gBrowser.getBrowserForTab(tab);
var canvas = document.createElementNS("http://www.w3.org/1999/xhtml",
"canvas");
canvas.setAttribute("anonid", "myCanvas");
canvas.setAttribute("height", "100%");
browser.parentNode.appendChild(canvas);
}
// Init all existing tabs first
var tabs = window.gBrowser.tabs;
for (var i = 0; i < tabs.length; i++)
initTab(tabs[i]);
// Listen to TabOpen to init any new tabs opened
window.gBrowser.tabContainer.addEventListener("TabOpen", function(event)
{
initTab(event.target);
}, false);
}, false)
Note that this code sets anonid attribute rather than id - an ID is supposed to be unique, you shouldn't assign the same ID to a dozen elements.
This won't work without an id. You could insert a piece of Javascript in the XUL document, that uses document.querySelector to find the tabpanels inside your XBL binding, and then would append the dynamically-created canvas to id.
However, since a new notificationbox is created every time a new tab is opened, you should have your javascript watch for new tabs and insert the canvasses accordingly.

How to select current page or by page id using jqmData

I have a multi-page document and I'm binding to the pageshow event of page "myId":
$('#myId').live('pageshow', renderMyIdTempalates);
I'm applying my JSON templates with PURE like this
function renderMyIdTempalates(event) {
$.mobile.showPageLoadingMsg();
var $page = $("#myId");
// do ajax call
$page.children( ":jqmData(role=header)" ).directives(...).render(data);
$page.children( ":jqmData(role=content)" ).directives(...).render(data);
$.mobile.hidePageLoadingMsg();
}
Initially I was using
$('#myId').directives(...).render(data);
to apply my templates. This caused problems since the selector didn't include the jqm attributes. So I used the jqmData method to grab the header and content to apply my templates. This works fine, but how do I select the entire document that I'm working with? I would prefer to apply my templates to the entire document once.
I tried:
$(":jqmData(role=page)") // selects all pages
$(":jqmData(id=myId)") // no luck
Any ideas?
the selector
div:jqmData(id="myID")
should work. just remember that myID should not be the id of that div.That page div should have a parameter data-id="myID"

Creating a jQuery UI sortable in an iframe

On a page I have an iframe. In this iframe is a collection of items that I need to be sortable. All of the Javascript is being run on the parent page. I can access the list in the iframe document and create the sortable by using context:
var ifrDoc = $( '#iframe' ).contents();
$( '.sortable', ifrDoc ).sortable( { cursor: 'move' } );
However, when trying to actually sort the items, I'm getting some aberrant behavior. As soon as an item is clicked on, the target of the script changes to the outer document. If you move the mouse off of the iframe, you can move the item around and drop it back by clicking, but you can not interact with it within the iframe.
Example: http://robertadamray.com/sortable-test.html
So, is there a way to achieve what I want to do - preferably without having to go hacking around in jQuery UI code?
Dynamically add jQuery and jQuery UI to the iframe (demo):
$('iframe')
.load(function() {
var win = this.contentWindow,
doc = win.document,
body = doc.body,
jQueryLoaded = false,
jQuery;
function loadJQueryUI() {
body.removeChild(jQuery);
jQuery = null;
win.jQuery.ajax({
url: 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js',
dataType: 'script',
cache: true,
success: function () {
win.jQuery('.sortable').sortable({ cursor: 'move' });
}
});
}
jQuery = doc.createElement('script');
// based on https://gist.github.com/getify/603980
jQuery.onload = jQuery.onreadystatechange = function () {
if ((jQuery.readyState && jQuery.readyState !== 'complete' && jQuery.readyState !== 'loaded') || jQueryLoaded) {
return false;
}
jQuery.onload = jQuery.onreadystatechange = null;
jQueryLoaded = true;
loadJQueryUI();
};
jQuery.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js';
body.appendChild(jQuery);
})
.prop('src', 'iframe-test.html');
​
Update: Andrew Ingram is correct that jQuery UI holds and uses references to window and document for the page to which jQuery UI was loaded. By loading jQuery / jQuery UI into the iframe, it has the correct references (for the iframe, rather than the outer document) and works as expected.
Update 2: The original code snippet had a subtle issue: the execution order of dynamic script tags isn't guaranteed. I've updated it so that jQuery UI is loaded after jQuery is ready.
I also incorporated getify's code to load LABjs dynamically, so that no polling is necessary.
Having played with their javascript a bit, Campaign Monitor solves this by basically having a custom version of jQuery UI. They've modified ui.mouse and ui.sortable to replace references to document and window with code that gets the document and window for the element in question. document becomes this.element[0].ownerDocument
and they have a custom jQuery function called window() which lets them replace window with this.element.window() or similar.
I don't know why your code isn't working. Looks like it should be.
That said, here are two alternative ways to implement this feature:
If you can modify the iframe
Move your JavaScript from the parent document into iframe-test.html. This may be the cleanest way because it couples the JavaScript with the elements its actually executing on.
http://dl.dropbox.com/u/3287783/snippets/rarayiframe/sortable-test.html
If you only control the parent document
Use the jQuery .load() method to fetch the content instead of an HTML iframe.
http://dl.dropbox.com/u/3287783/snippets/rarayiframe2/sortable-test.html
Instead of loading jQuery and jQueryUI inside the iFrame and evaluating jQueryUI interactions both in parent and child - you can simply bubble the mouse events to the parent's document:
var ifrDoc = $( '#iframe' ).contents();
$('.sortable', ifrDoc).on('mousemove mouseup', function (event) {
$(parent.document).trigger(event);
});
This way you can evaluate all your Javascript on the parent's document context.

Resources