Can I combine jQuery with Javascript? - javascript

I want to use the Javascript selector document.querySelector insted of $ or jQuery jQuery selector but I want to combine the Javascript selector with jQuery functions (like .getJSON(), .html(), .append() , etc.).
For example:
$.getJSON("list.json", function(data) {
document.querySelector("#content").html(data.name);
});
Here when I use the document.querySelector I get Uncaught TypeError: undefined is not a function and when I use $ I don't get any error.
jsFiddle Test
Is it possible to run jQuery and Javascript together?
Thanks!

Off couse yes! It is possible to run jQuery and JavaScript together in you application.
All you need to know is, which is a JavaScript Object when trying to run some methods of it. jQuery can be handy sometimes. But, yes! You can work with them together.
Secondly, remember that jQuery is a JavaScript's Library. It isn't anything other than JS. To be simple, jQuery needs JavaScript to run. JavaScript doesn't need jQuery to run.
From this MDN source, it is stated that you can use that method just the way it is.
document.querySelector(".someclass");
https://developer.mozilla.org/en-US/docs/Web/API/document.querySelector
All you now need to make sure is of that, that class you're trying to access exists.

$.getJSON("list.json", function(data) {
$(document.querySelector("#content")).html(data.name);
});
PS:
But there isn't any sense to use it everywhere. Check the #afzaal-ahmad-zeeshan answer & read how to use native functional of DOM elements. jQuery isn't a panacea.

jslayer's answer gave me an idea, which seems to work.
Wrapping js code in $() seems to work (though I'm not sure why).
For example, to use slideToggle() (which is only available in jQuery, I think), doing
event.target.nextElementSibling.slideToggle()
does not work, but
$(event.target.nextElementSibling).slideToggle()
does.

Related

Why can't I use jQuery in amazon (in console)?

using firebug console in firefox for example when execute this script
$("body").css("border","4px solid red");
it will return an error with message:
TypeError: $("body") is null
same in chrome the error:
TypeError: undefined is not a function
any one knows why? and how to use it?
$ is not a reference to jQuery at that site.
It does appear as though an old version jQuery is loaded...
You can tell by doing this...
jQuery.fn.jquery; // 1.2.6
Also, keep in mind that consoles are often not a pure environment. If there's no other code using the $ variable, they may take it over.
It appears as though Firebug does exactly that. I'm guessing it's a shortcut for document.getElementById, which will return null if there's no element with the ID "body".
The error is different in Chrome because $ is apparently undefined, so you're trying to use undefined as a function.
In the case of Amazon, only jQuery is defined, not $, you can use the jQuery() function instead of $() or simply define $=jQuery
Note the version of jQuery is an old one: 1.2.6
Edit
$=jQuery.noConflict() sounds even cleaner
As "am not i am" stated, Amazon either doesn't use jQuery or doesn't alias it as "$".
If you want to use jQuery on a site like that, you can use a jQuerify-ing bookmarklet like this one:
http://www.learningjquery.com/2009/04/better-stronger-safer-jquerify-bookmarklet
to add jQuery (with the standard "$" alias) to the page temporarily.

Convert JQuery to JavaScript

My knowledge of Jquery & Javascript is limited at best, but I'm under the impression JQuery is basically a simplified version of JavaScript.
If that is the case is there a way of converting this code to Javascript so I don't have to call the JQuery Library as it seems to be causing other JavaScript Functions to not work?
function toggleStatus(mynum) {
$('#product_'+mynum+'_submit_button').removeAttr('disabled');
}
This should work :)
var d = document.getElementById('product_'+mynum+'_submit_button');
d.removeAttribute('disabled');
jQuery is not a simplyfied version of javascript, but a javascript library that enables you to work rather effortlessly with the dom.
the code could be rewritten like that:
var e = document.getElementById('product_'+mynum+'_submit_button');
if( e ) e.removeAttribute('disabled');
The native version of that code would
set the disabled property on the element instead of messing with the attribute
use document.getElementById to select an element by id in lieu of jQuerys $("#id"):
var element = document.getElementById('product_' + mynum + '_submit_button');
element.disabled = false;
Also note that, for future reference, the native equivalent for jQuery's removeAttr is removeAttribute
Which other Javascript function's aren't working? jQuery is a Javascript framework to help you achieve Javascript tasks more easily, as well as create other functionality like animations.
If you're looking to simply convert what you have there into Javascript, you could do this:
function toggleStatus(mynum) {
document.getElementById('product_'+mynum+'_submit_button').removeAttribute('disabled');
}
I have a feeling like this could be the beginning of more Javascript and jQuery questions as you quest to learn more! Good luck! :)
Jquery is not simplified version of javascript. Think it as a library instead. The common functionalities which are needed for our development are simplified and organized in single library. For using that functionalities you have to read its API (Application Programming Interface) documentation. It will help you to write less code as compared to normal javascript code. I think, Jquery will not be the cause of problem in your code.
Any way for writing this code in pure javascript you can follow below code:
document.getElementById('buttonId').removeAttribute('disabled');

strange syntax in javascript to access a specific id in the dom

I am currently working on an old project with ton of legacy code.
A syntax I have never met is used to access a specific id in the dom in javascript.
Instead of using document.getElementById("btnsubmit"), $('btnsubmit') is used.
I have never met this syntax. Moreover it seems that firebug doesn't like it either as it seems to break the debugger. I have issues where the code doesn't seem to be executed in a debugging environment although this code is used on a production site and seems to work.
Does any one have a reference on this syntax? Where does it comes from, is it deprecated?
It's from a javascript library, and in general it's more modern than getElementById. You need the script include though.
Your example looks like Prototype
$ is just a regular character in javascript and it is often used by javascript libraries and defined to be a function name so that $() is just a function call. In some cases, $ might be defined to be a synonym for document.getElementById() as shorthand to save typing and in other cases, it's a more robust CSS3 style selector engine (as in the jQuery library).
In either case, if its undefined in your code, then you are probably missing a library reference that your code relies on. You will need to find out what library your code was written to use and make sure that library is included in the code before this spot so that the $() function is defined properly.

Finding if a jquery plugin/function is available. Diff between $.pluginName() and $().pluginName()

I am trying to detect if a jQuery plugin is available, I tried
$.pluginName
but failed then tried
$().pluginName
it works. But whats the difference between the 2?
You should be looking at $.fn.pluginName. jQuery's $.fn is an alias for $.prototype and that's where all the plugin names go. The top-level $.* namespace is reserved for jQuery's utility functions such as $.each() and $.grep().
You can look at this stackoverflow question only, they discussed a lot about this
How can I check if a jQuery plugin is loaded?

prototype and jQuery peaceful co-existence?

I know very little about JavaScript but despite this I'm trying to cobble something together on my wordpress blog. It's not working, and I don't know how to resolve it, and hey, that's what StackOverflow is for, right?
Firstly, the error message is:
Error: element.dispatchEvent is not a function
Source File: http://.../wp-includes/js/prototype.js?ver=1.6
Line: 3936
It happens on page load. My page load handler is registered thusly:
Event.observe(window, 'load', show_dates_as_local_time);
The error goes away if I disable some other plugins, and this (plus googling) led me to conclude that it was a conflict between prototype and jQuery (which is used by some of the other plugins).
Secondly I'm following the wordpress recommended practice of using wp_enqeue_script to add a dependency from my JavaScript to the Prototype library, as follows:
add_action( 'wp_print_scripts', 'depo_theme_add_javascript' );
function depo_theme_add_javascript() {
wp_enqueue_script('friendly_dates', 'javascript/friendly_dates.js', array('prototype'));
}
Now I'm also aware that there are some potential conflicts between jQuery and Prototype which are resolved using the jQuery noConflicts method. I've tried calling that from various places but no good. I don't think this is the problem because a) the noConflict function relates solely to the $ variable, which doesn't seem to be the problem here, and b) I would expect wordpress to sort it out for me because it can...
Lastly, using the Venkman debugger I've determined that the element referenced in the error message is indeed an HTMLDocument but also does lack a dispatchEvent. Not sure how this could happen, given it's a standard DOM method?
There is a nasty trick many libraries do that I've taken a distinct liking to, and it looks like prototype is one of these.
Mootools does this, If I am right, and it involves overloading many of the prototypes on the basic classes, monkey patching them.
And likewise, I similarly encountered strange behaviour when mootools and jQuery were present, usually jQuery dying because it was calling some object method which had been somehow overloaded/monkey patched by Mootools.
Also, mysteriously, taking mootools out of the script usage list, resulted in everything running much faster, which I concluded was due to less object pollution.
Now I could be wrong, but I concluded from my experience such libraries just simply don't like to co-exist with each other, and seeing how mootools code seemed to me to degrade speed at which normal things were done, I sucked up and ported all mootools based code to jQuery ( A time consuming deal I assure you ), and the result, was code that was fast and didn't have weird errors that were unexplainable.
I recommend you consider migration as at least One of your options.
One More thing, when writing:
I tend to use this syntax with all my jQuery driven code, for a bit of safe encapsulation in the event somebody breaks '$' somehow.
Runtime Code
This waits for document.ready before executing:
jQuery(function($){
code_with_$_here;
});
jQuery Plugins
(function($){
code_with_$_here;
})(jQuery);
Using these will make it easier for people using any jQuery you happen to write to be able to use it without much of a conflict issue.
This will basically leave them to make sure their code isn't doing anything really magical.
Its worth reading this article on the JQuery site about Using JQuery With Other Libraries. It deals with more than just the noConflict option.
I think you should search well because all jQuery plugins has a prototype version and all prototype plugins has a jQuery version.
If you really don't find what you look and you can't use only one library, take a look here at
jQuery.noConflict();
But again, i think it make no sense to load over 15-20kb for each library :)
Thanks for the suggestions all. In the end I think Kent's explanation was the closest, which basically amounted to "Prototype is broken". (Sorry if I'm summarizing you incorrectly :)
As for the jQuery.noConflict option - I already mentioned this in the question. It makes a difference when you run this method, and I have very little control over that. As I said, I have tried running it in a couple of different places (specifically the page header and also from my script file), to no effect. So, much as we'd all like it to be, "just use noConflict" is not an answer to this question, at least not without additional information.
Besides, jQuery.noConflict seems to be about the $ variable, and the code around the error point does not deal with that variable at all. Of course they could be related indirectly, I haven't tracked it down.
So basically I ended up rewriting the script using jQuery instead of Prototype, which actually had its own problems. Anyway I've published the whole war story on my blog, should you be interested.

Categories