Onclick not working. Cannot read property 'click' of null - javascript

I keep receiving the following error from the browser console when loading my script into my Magento store. All that it is listening for is an onclick event on a div yet I receive this error:
"Uncaught TypeError: Cannot read property 'click' of null."
The script works in JSfiddle so I'm really not quite sure why it isn't working. I've tried enclosing it within a $( document ).ready() as well but I receive the same error.
Code:
var step = 0;
var deviceType = "";
var modelType = "";
function showGen(){
$('.phoneTypes').css("display", "none");
if (deviceType == "Samsung"){
$('.sphoneGens').css("display", "block");
}
if (deviceType == "iPhone"){
$('.iphoneGens').css("display", "block");
}
if (deviceType == "iPad"){
$('.ipadGens').css("display", "block");
}
}
// Pick Device Type
$('.choicelabel').click(function(){
deviceType = $(this).children('input').val();
showGen();
});
//Pick Device Gen
$('.choiceType').click(function(){
modelType = $(this).children('input').val();
//$(".iphoneGens").css("display", "none");
console.log(deviceType);
console.log(modelType);
$(this).parents(".row").hide();
});
Any help debugging this issue will be greatly appreciated.

TL;DR:
jQuery( document ).ready(function( $ ) {
// Code using $ as usual goes here.
// And document is ready too
});
What's the issue?
Prototype.js was loaded after jQuery and was overwrite global $ symbol.
How can we deal with it?
You still have jQuery global to use. Just use it everywhere, where you want to use $.
// Pick Device Type
jQuery('.choicelabel').click(function(){
deviceType = jQuery(this).children('input').val();
showGen();
});
//Pick Device Gen
jQuery('.choiceType').click(function(){
modelType = jQuery(this).children('input').val();
//jQuery(".iphoneGens").css("display", "none");
console.log(deviceType);
console.log(modelType);
jQuery(this).parents(".row").hide();
});
You can also to define some shorthand for simplify it:
jQ = jQuery;
Common best practice for cases like this is to use IIFE wrap for your code:
;(function($){ // see note-1
// Use $ here! It's jQuery now
$(function(){
// be sure DOM was loaded before work with it(ex: binding events)
});
})(jQuery);
This adds nothing to global scope and achieves what we need.
You always can inject some other libraries(prototypejs?) with alias what you want to this IIFE.
note-1: Semicolon before IIFE protects javascript from previous expression with missed semicolon to be interpreted as function call.
jQuery itself provides shorthand for this case:
jQuery( document ).ready(function( $ ) {
// Code using $ as usual goes here.
// And document is ready too
});

That site isn't using jQuery, it's using prototypejs

Related

what is the proper mode to load basic jquery document:ready event? [duplicate]

I've seen four different ways to tell jQuery to execute a function when the document is ready. Are these all equivalent?
$(document).ready(function () {
alert('$(document).ready()');
});
$().ready(function () {
alert('$().ready()');
});
$(function () {
alert('$()');
});
jQuery(function ($) {
alert('jQuery()');
});
There is no difference.
$ is the same as jQuery. If you view the unminified source, you will see var $ = jQuery = ... or something to that effect.
The jQuery function checks the type of it's parameter, if it is a function, it treats it the same as $(document).ready(...)
Calling jQuery without a parameter defaults to using document. So $() and $(document) are identical. Try it in Firebug.
re: Geroge IV's comments regarding $() == $(document) its correct. From the unminified source (init is what get called internally):
init: function( selector, context ) {
// Make sure that a selection was provided
selector = selector || document;
Also from source, to back up previous conversations:
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) )
return jQuery( document ).ready( selector );
this should be community wiki. I've always been interested in the inner workings of jquery, now I've had an excuse to start looking :-)
Also it should be mentioned, that symbol that you pass to function will be use inside the function. For example:
$(function(jQuery) {
// now I can use jQuery instead $
jQuery("body").append("<div></div>"); // adds div to the end of body element
});
if you want use $ - you can leave function's param in this situation empty
The real example you can find here http://jsfiddle.net/yura_syedin/BNgd4/
Here's another one - starts like this...
(function (jQuery) {
then to finish...
})(jQuery);
An example is here:
http://jsfiddle.net/C2qZw/23/

Understanding jQuery & Pub Sub Pattern with this example

I use jQuery for some time, but that is usually very simple jQuery. I just watched some video tutorial in which the author uses something called Pub Sub Pattern. I've never heard of it before, so I have searched on Stackoverflow and Google for explanations:
Why would one use the Publish/Subscribe pattern (in JS/jQuery)?
But it's still not clear to me, especially because of the code that is used by the author of the above mentioned tutorial. So, I will paste this code here and if you can give me explanations:
1. Here is the first .js file named pubsub.js, and I don't understand it:
(function($) {
var o = $({}); // ??? what is this ???
$.subscribe = function() { // ??? and this ???
o.on.apply(o, arguments); // ??? o.on.apply(o, arguments) ???
};
$.unsubscribe = function() { // ??? and this ???
o.off.apply(o, arguments); // ??
};
$.publish = function() { // ??? and this ???
o.trigger.apply(o, arguments); // ?? o.trigger.apply(o, arguments); ??
};
}(jQuery));
I know that with jQuery you can use $( document ).ready() or $(function() but I've never seen (function($) { ... }(jQuery)); - what does this mean/do? Also, I don't understand the rest of the code...
2. The next file is app.js and it contains:
(function() {
$.subscribe('form.submitted', function() {
$('.flash').fadeIn(500).delay(1000).fadeOut(500);
})
});
What does this actually do? Again, what (function() { ... }); means/do? And as for the rest of code, can you explain to me $.subscribe('form.submitted', function() {?
3. Finally, we have something like this:
$.publish('form.submitted', form); // publish?
This also is not clear to me.
I understand that all this is a basic implementation of PubSub Pattern with jQuery, but I still don't get why would someone do in this way (by using this pattern), I have read that answer on Stackoverflow, but it's still unclear to me... I guess that if I understand this code, then it would become clearer to me why and when to use this pattern.
In the case of (function($) { ... }(jQuery));, the author is passing the jQuery instance in as a parameter. Inside the function (which has it's own scope), the $ is a reference to the jQuery instance that was passed in.
"Pub Sub" is just another term for Event Management, or Event Handling. All you're saying is "When [this] happens, do [that]".
When you "subscribe", you are passing in 2 parameters, the "event" that you are listening for, and the code you want to run when the event "fires".
When you "publish", you are "firing" (or triggering) that event.
Think of it like the onclick event. When you set something up on the onclick event, you are subscribing to that event. When you click, you are publishing that event.

How can I determine whether jQuery is fully initialized?

I'm writing a bookmarklet using jQuery. It looks like javascript:document.write('<script src="path/to/loader.js"></script>'), and loader.js does the initializing stuffs:
check_the_environment();
document.head.innerHTML='<meta charset=utf-8>';
document.body.innerHTML='(the webpage)';
var jq=document.createElement('script');
jq.src='path/to/jquery.min.js';
document.head.appendChild(jq);
function load_core() {
if(window.$)
eval('(core js code)');
else
setTimeout(load_core,50);
}
load_core();
The loader loads the core javascript code after the jQuery is available.
But sometimes I get this error in my core code:
$(...).on is not a function
It seems that jQuery was still initializing itself although $ variable is setted.
So, I need to wait for jQuery to be completely initialized before the loader loads the core code. How can I do that?
The traditional way of using $(document).ready(...) is infeasible, as jQuery is being loaded after the webpage is ready.
Here is a minimal Python code to check whether the solution is working:
import cherrypy
mod='''
var htmlroot=document.getElementsByTagName('html')[0];
function load_core() {
if(window.jQuery)
jQuery(function(){
alert($(document).on);
});
else
setTimeout(load_core,10);
}
if(!document.head)
htmlroot.appendChild(document.createElement('head'));
var jquery=document.createElement('script');
jquery.src='http://libs.useso.com/js/jquery/2.1.1/jquery.min.js';
document.head.appendChild(jquery);
load_core();
'''
class Website:
#cherrypy.expose()
def mod(self,_time):
return mod
#cherrypy.expose()
def index(self):
return '''Mod'''
cherrypy.quickstart(Website(),'/');
The right and foolproof way would be:
jQuery(function(){
// code
});
Since jQuery may be loaded in noConflict mode the $ var may not have been initialized.
For the sake of productivity the following can also be used to have access to $ var inside the jQuery scope.
jQuery(function($){
// you can use $ without worrying about conflicts now
});
You can check type of $ as below
if(typeof $ == "function"){
//Jquery loaded
}

Why doesn't this jQuery image map not work on WordPress

Hello I have made a jQuery image map on codepen but when I transfer it to my clients WordPress install it no longer works?
The WordPress site is made with genesis and I thought that may be causing the problem... I also replaced $ with jQuery to stop conflict problems.
Pen: http://codepen.io/naniio/pen/QwVXWG
jQuery:
jQuery(document).ready(function($) {
jQuery(".clickable").click(function() {
var toHide = $(this).attr('data-hide');
jQuery(".map").toggle();
jQuery("#" + toHide).toggle();
});
jQuery(".hide").click(function() {
jQuery(".map").toggle();
jQuery(this).toggle();
});
});
Site www.shakesafe.co.nz
I added the code (HTML + JS) the home page with simple hooks and then added the CSS with a custom body tag for the home page in gensis samples stylesheet.. but the Jquery doesn't work? do you guys have any ideas as to why?
Thanks for your time and effort as always!
Always check your browser console for errors thrown. In this case, I see a Uncaught TypeError: undefined is not a function message. That error is found on line 112 on your page, and if you check it carefully, you are using the $ without assigning the jQuery object to it, hence causing an error:
jQuery(document).ready(function() {
jQuery(".clickable").click(function() {
var toHide = $(this).attr('data-hide'); // Line 112 where error is from
jQuery(".map").toggle();
jQuery("#"+toHide).toggle();
});
jQuery(".hide").click(function() {
jQuery(".map").toggle();
jQuery(this).toggle();
});
});
Replace the $ with jQuery, i.e. var toHide = jQuery(this).attr('data-hide');.
Alternatively, you can tell jQuery that you are using $ to stand in for the jQuery object, saving you 5 characters every single instance you call for it:
jQuery(document).ready(function($) {
$(".clickable").click(function() {
var toHide = $(this).attr('data-hide');
$(".map").toggle();
$("#"+toHide).toggle();
});
$(".hide").click(function() {
$(".map").toggle();
$(this).toggle();
});
});
May be it's because of $ on 3rd line:
var toHide = $(this).attr('data-hide');
Try changing it to jQuery. It may work.
Also your site had no $ on your code:
jQuery(document).ready(function() {
try putting $ between small braces after function

Different behavior with JQuery 1.4.4 and 2.1.1 (scroll top)

Don't ask me why, but a developer I commissioned used JQuery 1.4.4 to set up a couple functions on a page, and I am trying to update the JQuery version to 2.1.1. Doing this, I am getting a couple JS errors that are dealing with scrolling, namely:
$(document).ready(function(){
var scroll_pos = 0;
$(document).scroll(function() {
scroll_pos = $(this).scrollTop();
var hrt = $('.boxBg').offset().top-200;
if(scroll_pos > hrt) {
$('i.fa-heart').addClass('individual-heart-hover');
}
else{
$('i.fa-heart').removeClass('individual-heart-hover');
}
});
});
and
var _rys = jQuery.noConflict();
_rys("document").ready(function () {
_rys(window).scroll(function () {
if (_rys(this).scrollTop() >100) {
_rys('.navbar').addClass("f-nav");
_rys('.discoverSection').addClass("f-nav2");
$('.tabsection').css('display','block');
} else {
_rys('.navbar').removeClass("f-nav");
_rys('.discoverSection').removeClass("f-nav2");
$('.tabsection').css('display','none');
}
});
});
The lines that are receiving errors are:
$(document).ready(function(){
and
$('.tabsection').css('display','block');
both are receiving errors saying "Uncaught TypeError: undefined is not a function".
Strangely, these both work flawlessly with JQuery 1.4.4.
This line is suspicious:
var _rys = jQuery.noConflict();
That code removes the definition of $, so any subsequent code that uses $ will fail.
You should only use jQuery.noConflict() if you need to load two different versions of jQuery simultaneously, or if you are using another library that defines $ to mean something else. (.noConflict() actually restores any previous definition of $, but from the error you received it looks like there was no previous $.)
Assuming you are not dealing with one of those special situations, simply remove the noConflict line completely, and then change every instance of _rys to $.

Categories