Reputation: 545
I found some promising code to do random background css color and invert the text color but can not seem to get this to work. Any help is greatly appreciated.
$(document).ready(function() {
var colors = ['#000000', '#FF3516', '#34FF17', '#2458FF'];
function UpdateColors() {
$(this).each(function(index) {
var color = colors[Math.floor(Math.random() * colors.length)];
var invertedColor = invertColor(color);
$(this).css({
'background-color': color,
'color': invertedColor
});
});
}
//$('div').UpdateColors();
});
Fiddle here:
https://jsfiddle.net/abennington/h49zh3gy/10/
Upvotes: 0
Views: 518
Reputation: 8422
You need to be calling your css()
method on a specific element or set of elements; $(this)
won't work in the context in which you're using it.
So, since it looks like you're trying to do this for every element:
$(document).ready(function() {
var colors = ['#000000', '#FF3516', '#34FF17', '#2458FF'];
$("*").each(function() {
var color = colors[Math.floor(Math.random() * colors.length)];
var invertedColor = invertColor(color);
$(this).css({ 'background-color': color, 'color': invertedColor });
});
});
If you want to just do this on the body element, replace "*"
with "body"
.
(I'm assuming that your invertColor()
function works.)
Edit: I think I missed your point a little. Once you extend $
, you'll be able to call your function as you're doing in your commented-out call at the bottom. However, my code still works if you don't want to go the (in my opinion, slightly more fiddly) route of screwing around with $
.
Upvotes: 2
Reputation: 621
You weren't extending jQuery so it couldn't see the $('div').UpdateColors() function.
I've tweaked that so you can use the function that way: jQuery.fn.UpdateColors = function () { ... }
See this fiddle https://jsfiddle.net/h49zh3gy/11/
However you will still get an error as the invertColor function is not defined anywhere.
Upvotes: 2