jQuery in Opera User JS Doesn't Work - javascript

). I'm playing with some Opera User JS. I included "1jquery.min.js" in my User JS folder (1 in front because Opera loads them alphabetically). Unfortunately, it doesn't appear to be working.
window.onload = OnWindowLoad;
$(document).ready(function()
{
alert ($('#area_19'));
});
function OnWindowLoad ()
{
alert ($('#area_19'));
alert(document.getElementById("area_19"));
}
What's interesting about this code is that the first two alerts come back in NULL, but the last one does find the object! So the element definitely exists in the page, but my jQuery seems unable to get it. What's even stranger is that the jQuery "ready" function works, indicating that I do have jQuery capability.
I'm quite puzzled about all this ::- /. Hopefully somebody can give me a clue ::- ).

I suspect you are running the script on a page that uses another JS framework, probably Prototype.js.
If Prototype were included by the target page it would overwrite your jQuery copy of $ with its own that gets an element by ID, not selector. Since there is no element with ID #area_19 (# not being a valid character in an ID), it would return null. jQuery would never return null for a non-existant element, you'd only get an empty wrapper object.
(The $(document).ready() code would still execute because the $ was called before Prototype was included and changed the behaviour of $.)
Try using the explicit jQuery function rather than the $ shortcut.
These sorts of interferences are common when mixing multiple frameworks, or even mixing two copies/versions of the same framework. From jQuery's side its interactions can be reduced, but not eliminated, with noConflict. Personally for code like user scripts that might have to live in a wide range of contexts not controlled by myself, I would avoid using wide-ranging frameworks like jQuery.

Related

jQuery & Prototype Conflict (Javascript Debugging)

We have a Magento store setup which seems to have an existing jQuery & Prototype conflict going on. When you access our URL here, it'll take a few moments and then load a single product (a wheel). If you click onto the image, it is intended that it'd bring up a lightbox but it just opens the image in the tab due to this conflict. I can even see an error is going into the console log, but don't know how to pause it so that I can see the error (it's too quick).
If I don't have an attribute checked off on the left, the image lightbox works fine. I know the image lightbox is powered by jQuery, and the layered navigation by Prototype. This is my reason for believing it's an issue with that. :-)
In your Javascript code, add a line like this to run jQuery in no-conflict mode:
var $jQ = jQuery.noConflict();
Then, wherever you use jQuery, instead of using the default "$" symbol in a selector, use "$jQ" instead: for example,
$jQ([jQuery selector]).[jQuery function]();

jQuery - check if .noconflict has been triggered

I'm loading a jQuery script dynamically into random pages.
Sometimes they support jQuery, sometimes they have other libraries and sometimes they don't have any library at all..
I need to support all cases, therefore, first I check if jQuery has loaded.
Case not, I load jQuery dynamically into the page using .noconflict (to avoid conflicts in case there are other libraries there, daahhh) and then just continue with my script.
Case it's already been loaded, I need to know if the page has triggered the .noconflict function or not.
Why ? it's simple.
Let's say a random page have both Prototype and jQuery (happens, yes).
The webmaster trigger the .noconflict mode for the jQuery, to avoid conflicts with it.
After that, I trigger my script, and check if jq has been loaded (yes).
And then, I have to know weather to use $() or jQuery() methods, since if I'll continue using $() I might access the Prototype handler,
And I don't want that.
.noConflict only removes the $ object and not the jQuery object. (Except if you add true as first parameter.
So you can always use jQuery()
you can use:
jQuery(function( $ ){
//Insert your javascript code here
});
and all of your jQuery code will be in these braces and will never conflict with other prototypes.
As everyone else said, you should just always default to using the full jQuery object instead of the alias. If it's a quantity-of-typing issue, use $ and then find-replace in your text editor before pushing to live.
...But if you absolutely, positively MUST do this the ridiculous way, it's simple:
​if​ ($ == jQuery) { alert("YAY"); }​​​​​​
Here's an example I cooked up on JSFiddle using jQuery 1.8 and a separately-loaded MooTools 1.4.5: http://jsfiddle.net/fL9rk/2/
Run it once, then unload the external MooTools and try again.
Don't say we didn't warn you.

How to Debug javascript and jquery with firebug

I just installed firebug and want to see and debug jquery and javascript methods when fired.
Suppose that a jquery function will be called when button is clicked. When the site is huge and the page includes many js files then it is very difficult to point out which function will be called and where it is defined, because people attach button events in a different way. I mean the event is attached sometime based on css. So sometimes I just cannot find out which method is going to be invoked.
So please give me some tips so that I can see those functions invoke and the function body at run time wherever it is defined. Thanks.
You can try using FireQuery. From the site:
jQuery expressions are intelligently presented in Firebug Console and DOM inspector
attached jQuery data are first class citizens
elements in jQuery collections are highlighted on hover
jQuerify: enables you to inject jQuery into any web page
jQuery Lint: enables you to automatically inject jQuery Lint into the page as it is loaded (great for ad-hoc code validation)
I've used it a few times and it makes debugging (when using jQuery) much easier.
EDIT
Using the plugin, you can look at the element and see the events bound to it. Your other option is to search your codebase for anything that identifies the element (id or css class perhaps). Then you should also be able to see what gets bound.
Take a look at http://firequery.binaryage.com/ (FireQuery). It's an extension to FireBug that allows you to see jQuery calls. I haven't used it that much, but it might be what you're looking for.

Must I specify endding tag with jquery.append()?

I am studying somebody else jquery script, and I noticed he is opening a tag without closing it, but it also seems that browsers does not care (Not yet tested with IE)
it is written :
$('#mydiv').append('<ul>')
But there is nowhere a
.append('</ul>')
The script does not close the list, but browsers do it automatically (I just did an 'inspect element' in the browser).
Is that a 'legal' behavior, or one should always close a tag in a javascript autogenerated content ?
To do it properly, you should be appending:
$('#mydiv').append('<ul></ul>')
Yes browsers will handle it (specifically the .innerHTML implementation handles it, not jQuery), at least the major ones, but why not be safe in all cases and use valid markup?
$('#mydiv').append('<ul>')
...still calls .innerHTML, not createElement, only in $('<ul>') is document.createElement() called. As I said originally, the browser handles it with .append(), not jQuery and not document.createElement (which doesn't take syntax like this anyway).
You can see test/play with what I mean here
Short answer: you should.
Long answer that lead to the short answer:
When you say .append('<ul>'),
or even .append('<ul></ul'), behind the scenes jQuery calls document.createElement and the browser knows what to do.
It's not like jQuery actually puts that string of HTML anywhere, but rather parses it and creates the necessary DOM elements
UPDATE-
As Nick pointed out, this might not always be the case. Relevant source: init
If you pass it just ul, it just calls createElement. If the html string is more complicated, it will go into buildFragment which is more complicated than that.
Based on this, I would say the best/fastest way to create a single element thru jQuery, is to do something like
$('<ul>').appendTo($target);
UPDATE 2-
So apparently jQuery only calls createElement in some methods, but append ends up calling clean which has a regex that closes tags. So either way, you're safe, jQuery saves you as usual.
Relevant source:
...
} else if ( typeof elem === "string" ) {
// Fix "XHTML"-style tags in all browsers
elem = elem.replace(rxhtmlTag, "<$1></$2>");
...
UPDATE 3- So it turns out jQuery doens't fix anything for you when you call append, and it just injects the string into a temporary div element. Seems like most browsers know how to deal with the HTML even if not closed properly, but to be save it's probably best to close it yourself! Or if you're feeling lazy, do something like .append($('<ul>')) which doesn't use innerHTML

Work with AJAX response with DOM methods

I'm retrieving an entire HTML document via AJAX - and that works fine. But I need to extract certain parts of that document and do things with them.
Using a framework (jquery, mootools, etc) is not an option.
The only solution I can think of is to grab the body of the HTML document with a regex (yes, I know, terrible) ie. <body>(.*)</body> put that into the current page's DOM in a hidden element, and work with it from there.
Is there an easier/better way?
Update
I've done some testing, and inserting an entire HTML document into a created element behaves a bit differently across browsers I've tested. For example:
FF3.5: keeps the contents of the HEAD and BODY tags
IE7 / Safari4: Only includes what's between ...
Opera 10.10: Keeps HEAD and everything inside it, Keeps contents of BODY
The behavior of IE7 and Safari are ideal, but different browsers are doing this differently. Since I'm loading a predetermined HTML document I think I'm going to use the regEx to grab what I want and insert it into a DOM element - unless someone has other suggestions.
Elements can exist without being in the page itself. Just dump the HTML into a dummy div.
var wrapper = document.createElement('div');
wrapper.innerHTML = "<ul><li>foo</li><li>bar</li></ul>";
wrapper.getElementsByTagName('li').length; // 2
Given your edits, we run into a sticky situation, since you want getElementById. The matter would probably be easy if you could just create a new virtual document via document.implementation.createDocument, but IE doesn't support that at all.
Using a regex is a messy business, since what if we see something like <body><input value="</body>" /></body>? You could probably just make your regex greedy so that it moves on to the last instance of </body>, but if you do end up running into troubles, a more thorough parsing may be necessary. Even if a full framework isn't an option, you might end up wanting to use something like Sizzle, the core of libraries like jQuery, to look for the element you want. Or, if you're really feeling in a purist sort of mood, you could write the recursive search function yourself - but why take that hit if someone else has already taken it?
var response_el = document.createElement('html'), foo;
response_el.innerHTML = the_html_elements_content;
foo = Sizzle('#foo', response_el);

Categories