Skip to content Skip to sidebar Skip to footer

Onclick Not Working. Cannot Read Property 'click' Of Null

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

Solution 1:

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 TypejQuery('.choicelabel').click(function(){
    deviceType = jQuery(this).children('input').val();
    showGen();
});

//Pick Device GenjQuery('.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
});

Solution 2:

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

Post a Comment for "Onclick Not Working. Cannot Read Property 'click' Of Null"