blackhawk blackhawk - 6 months ago 10
Javascript Question

How to properly use $ inside functions / self invoking, that are part of a noConflict process via jQuery?

With the following code, I would like to use $ inside of function declarations, that are then referenced inside of a self invoking function. How can I do this process when using noConflict()? When I run the following code I get "Uncaught TypeError: $ is not a function"

//I have jQuery 2.2.4 linked at the bottom of my page like this...

//<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="crossorigin="anonymous"></script>

//then my code...

var jq224 = $.noConflict();

function dosomething(){
$("#wrapper").append('<p>connect me</p>');
}

function doanotherthing(){
$("#someid").append('<p>show me something more</p>');
}

(function($) {
dosomething();
doanotherthing();
}(jq224));


Why does the above process throw an error? But if I do the following, it does not throw an error...

(function($) {
$("#wrapper").append('<p>connect me</p>');
}(jq224));

Answer

After you call noConflict the "previous" reference of $ is restored. Since $ was not previously declared, it's now unknown.

You can however pass $ to the functions you're calling:

var jq224 = $.noConflict();

function dosomething($) {
  $("#wrapper").append('<p>connect me</p>');
}

function doanotherthing($) {
  $("#someid").append('<p>show me something more</p>');
}

(function($) {
  dosomething($);
  doanotherthing($);
}(jq224));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

<div id='wrapper'>wrapper</div>
<div id='someid'>someid</div>