Reputation: 2044
I have some JQuery that loads one of many elements, for example one <li>
in an unordered list out of many rows of list items as such:
this.randomtip = function(){
var length = $("#tips li").length;
var ran = Math.floor(Math.random()*length) + 1;
$("#tips li:nth-child(" + ran + ")").show();
};
$(document).ready(function(){
randomtip();
});
However, I thought it would be nice to convert this to a JQuery plugin to make it more global in use so I could simply call it when I need it for different elements and use cases.
I realized I needed to take the specific selectors out and convert them to $(this)
probably based on looking at some code of other JQuery plugins.
This is what I have so far but am getting alot of syntax errors. I have tried many different iterations of the same thing for several hours but no joy:
(function ( $ ) {
$.fn.randomtip = function () {
var length = $(this).length;
var ran = Math.floor(Math.random()*length) + 1;
$(this).find (':nth-child' '+ ran + ')").show();
})(jQuery);
Where I am getting the syntax error is where I have:
$(this).find (':nth-child' '+ ran + ')").show();
Upvotes: 0
Views: 98
Reputation: 53198
You have a few typos on the $(this).find()
line. Below is the correct version:
(function ( $ ) {
$.fn.randomtip = function () {
var length = $(this).length;
var ran = Math.floor(Math.random() * length) + 1;
$(this).find (':nth-child('+ ran + ')').show();
})(jQuery);
Upvotes: 2
Reputation: 41050
There is a syntax problem in
$(this).find (':nth-child' '+ ran + ')").show();
Maybe you want this?
$(this).find (':nth-child(' + ran + ')').show();
Upvotes: 0