I am trying to display the letters of the alphabet(randomly) as background images for divs using Jquery and CSS, however, I want the letters to be random per element, but I am only able to randomise this for all images at the same time:
HTML:
<div class="randbg"></div>
<div class="randbg"></div>
<div class="randbg"></div>
<div class="randbg"></div>
JS
(function($) {
$.fn.RandBG = function(options) {
var settings = $.extend({
ClassPrefix: "bg",
count: 26
}, options);
var index = Math.ceil(Math.random() * settings.count * settings.count) % settings.count;
$(this).addClass(settings.ClassPrefix + index);
};
}(jQuery));
CSS
.randbg {
margin:20px auto;
font-family: 'Parkour';
color:red;
width:180px;
height:180px;
}
.randbg:before {
display:block;
font-size:10em;
text-align: center;
vertical-align: center;
background-color:#EDEDED;}
.randbg.bg0:before {
content:"z";
}
.randbg.bg1:before {
content:"a";
}
.randbg.bg2:before {
content:"b";
}
.randbg.bg3:before {
content:"c";
}
.randbg.bg4:before {
content:"d";
}
.randbg.bg5:before {
content:"e";
}
.randbg.bg6:before {
content:"f";
}
.randbg.bg7:before {
content:"g";
}
.randbg.bg8:before {
content:"h";
}
.randbg.bg9:before {
content:"i";
}
.randbg.bg10:before {
content:"j";
}
.randbg.bg11:before {
content:"k";
}
.randbg.bg12:before {
content:"l";
}
.randbg.bg13:before {
content:"m";
}
.randbg.bg14:before {
content:"n";
}
.randbg.bg15:before {
content:"o";
}
.randbg.bg16:before {
content:"p";
}
.randbg.bg17:before {
content:"q";
}
.randbg.bg18:before {
content:"r";
}
.randbg.bg19:before {
content:"s";
}
.randbg.bg20:before {
content:"t";
}
.randbg.bg21:before {
content:"u";
}
.randbg.bg22:before {
content:"v";
}
.randbg.bg23:before {
content:"w";
}
.randbg.bg24:before {
content:"x";
}
.randbg.bg25:before {
content:"y";
}
What is the best way to make each randbg div display a random letter?
Thanks
The problem is your plugin. You're applying the same class to all matched elements. I'm assuming you're calling it like this
You have several options but I'd probably use the callback version of
addClass()
You should also remember to always return the jQuery collection (
this
) from plugin functions so they're chainable.JSFiddle