Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Maja B.
12,984 PointsWhy is my jQuery not responding?
I have a very simple code written in my JS file:
$("#imageGallery").click(function(){
alert ('hello');
});
As far as I understand jQuery this should open an alert box with the text hello, when I click on the element with an id="imageGallery". But it does not.
Even if I write it like this:
$( document ).ready(function() {
$("#imageGallery").click(function(){
alert ('hello');
});
});
... it does not
Besides, if I inspect the element with Chrome the first line of each one of the above code examples is underlined with red.
So what could be wrong?
1 Answer
eck
43,038 PointsYour code looks good, so the problem could be that jQuery is not loaded properly. Try writing "$('body')" in the Chrome Dev Tools console and see if the body element is returned. If it isn't, then jQuery has not been linked to properly. You could also try writing "jQuery('body')" if the first test returned undefined.
If that was all good, then maybe your custom js file that you are writing is not properly linked to.
Maja B.
12,984 PointsMaja B.
12,984 PointsHi, Erik,
in Chrome Dev Rool Console
$('body') returns: Uncaught TypeError: undefined is not a function VM2094:2(anonymous function) VM2094:2InjectedScript._evaluateOn VM2090:732InjectedScript._evaluateAndWrap VM2090:665InjectedScript.evaluate
jQuery('body') retrns the body itself - so it works fine
Some more info to help you help me:
I'm working in WordPress. I have a child theme php-child and I enqueue custom.js (in which the code from my question above is written) like this:
Does that give you any new idea?
eck
43,038 Pointseck
43,038 PointsAh, my suggestion is to use "jQuery" instead of "$". Since other js libraries also use $, it is safer to use the longer name for the jQuery object, to prevent confusing for the browser.
You will want js that looks like this:
Maja B.
12,984 PointsMaja B.
12,984 PointsOk. Great ... Thanks!! Maja
eck
43,038 Pointseck
43,038 PointsAlso, if you want to read an article with a bit more detail, you can check this out :)
Maja B.
12,984 PointsMaja B.
12,984 PointsOk, following your article (plus having in mind that in my project jquery scripts are enqueued in the <head> section) I've wrapped my code into
So now the $ sign works. Thank you, Maja