Reputation: 81
I have implemented this code into my website (which randomizes/shuffles divs order):
function shuffle(array) {
var currentIndex = array.length
, temporaryValue
, randomIndex
;
while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
$.fn.randomize = function (childElem) {
return this.each(function () {
var $this = $(this);
var elems = shuffle($(childElem));
$this.remove(childElem);
for (var i = 0; i < elems.length; i++)
$this.append(elems[i]);
});
}
jQuery(function($){
$("div.container").randomize("div.random");
});
However it is not working due to conflict with other script, and I assume that $.noConflict(); is the case.
Here is the fiddle, http://jsfiddle.net/7L4gu/ i have hard times working it out myself, I will highly appreciate your help!
Upvotes: 0
Views: 119
Reputation: 781139
When you use jQuery.noConflict()
, you can't use $
outside the jQuery(function($){...}
block. You need to change $.fn.randomize = ...
to jQuery.fn.randomize = ...
, or put the function definition inside the jQuery
call. You also need to change $(this)
and $(childelem)
to jQuery(this)
and jQuery(childelem)
inside the randomize
function.
Upvotes: 2
Reputation: 388316
It is because of noConflict(), once you use it $
does not refer to jQuery anymore. In your fiddle the value of $
undefined once you call noConflict()
so the expression $.fn
will fail.
A solution which is widely used is to use an IIFE like
(function ($) {
$.fn.randomize = function (childElem) {
return this.each(function () {
var $this = $(this);
var elems = shuffle($(childElem));
$this.remove(childElem);
for (var i = 0; i < elems.length; i++)
$this.append(elems[i]);
});
}
})(jQuery)
Demo: Fiddle
In this case inside the IIFE method we are receiving the jQuery object as an argument and it is named as a local scoped variable $
so that we can use the shorter form in the plugin.
Upvotes: 1