How to randomly assign a color on hover effect - html

I've never seen a hover effect like this before, and I'm trying to understand how it's achieved. You'll notice in this example, that when a user hovers over a link, the color the link turns can be any one 1 of 5 colors that are assigned within the style sheet (see below) at random.
How do you create this hover effect? Can it be done purely with CSS?
a:hover {
color:#1ace84;
text-decoration: none;
padding-bottom: 2px;
border: 0;
background-image: none;
}
a.green:hover { color: #1ace84; }
a.purple:hover { color: #a262c0; }
a.teal:hover { color: #4ac0aa; }
a.violet:hover { color: #8c78ba; }
a.pink:hover { color: #d529cd; }

Since a random factor is introduced, I don't think there's a way of doing it purely with CSS.
Here's my simple approach to the problem, using jQuery.
You can see a working example here: http://jsfiddle.net/GNgjZ/1/
$(document).ready(function()
{
$("a").hover(function(e)
{
var randomClass = getRandomClass();
$(e.target).attr("class", randomClass);
});
});
function getRandomClass()
{
//Store available css classes
var classes = new Array("green", "purple", "teal", "violet", "pink");
//Get a random number from 0 to 4
var randomNumber = Math.floor(Math.random()*5);
return classes[randomNumber];
}

The key piece of jQuery code is loaded in the footer of the page.
Please pay attention to the authors comment on the script, or seek the author's permission to reuse it.
/*
Code below this point is not licensed for reuse,
please look and learn but don't steal
*/
var lastUsed;
function randomFrom(arr){
var randomIndex = Math.floor(Math.random() * arr.length);
lastUsed = arr[randomIndex];
return lastUsed;
}
color_classes = ['green','purple','violet','teal','pink'];
function initLinks() {
$('#wrap a').hover(function() {
new_classes = color_classes.slice();
var index = $.inArray(lastUsed, new_classes);
new_classes.splice(index, 1);
var classes = $(this).attr('class');
if (classes) {
classes.split(' ');
$(classes).each(function(i, className) {
var index = $.inArray(className, new_classes);
if (index>0) {
new_classes.splice(index, 1);
}
});
}
$(this).removeClass(color_classes.join(' ')).addClass(randomFrom(new_classes));
}, function () {
});
}

Related

Generating the same 2 random colors for 2 different objects

Basically, I have to generate the same color, chosen randomly, for 2 different bodies. Does anyone have any tip on how I could link the two objects to have the same random colour? Evertime a condition happens, the colour should refresh and both bodies should have that particular colour.
Thx a lot!
//btw any code language is useful
The simple solution is to generate the random color once and then set the color of both bodies to that color. Put that in a refreshColors function and call that function when your condition is met.
if (condition) {
refreshColors()
}
function refreshColors () {
// generate color
let color = generateRandomColor()
// set Body A color
body_a.style.color = color
// set Body B color
body_b.style.color = color
}
I recommend using a custom property (also known as CSS variables):
function randomColor() {
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
return `rgb(${r},${g},${b})`;
}
const root = document.documentElement;
root.style.setProperty("--random-color", randomColor());
.element-1,
.element-2 {
background-color: var(--random-color);
}
<p class="element-1">Element 1</p>
<hr />
<p class="element-2">Element 2</p>
If you want you can set the custom property to some default value in your CSS file:
:root {
--random-color: rebeccapurple;
}
And make sure your elements use this property, using the CSS var() function:
.element-1,
.element-2 {
background-color: var(--random-color);
}
Then you overwrite that property in you if statement using style.setProperty:
if (condition) {
const root = document.documentElement;
root.style.setProperty("--random-color", randomColor());
}
Read more about dynamically setting custom properties in this article.

How to change the color of a diagram cell while hovering?

I have an uml diagram and I want to change the color of one cell when the cursor is on it.
I tried to do it programmatically, but it doesn't work.
Here's my code:
paper.on('cell:mouseover', function(cellView, evt, x, y) {
var cell = graph.getCell(cellView.model.id)
if (cell.isElement()) {
cellView.model.attr({'uml-class-name-rect': { fill: '#33C3FF' }});
}
}
paper.on('cell:mouseenter', function(cellView) {
var cell = graph.getCell(cellView.model.id);
if (cell.isElement()) {
cellView.model.attr({'.uml-class-name-rect': { 'fill': '#33C3FF' }});
}
});
CSS of class 'uml-class-name-rect' can't be set simultaneously through a global css file.

ES6 Classes with GSAP says can't Tween null object

My code is as below. Any ideas how can I call this.rule ? I am trying to use GSAP's TweenMax with a plugin called CSSRulePlugin to animate the pseudo elements.
class animate {
constructor() {
this.rule = CSSRulePlugin.getRule(".menu a:before");
this.target = document.querySelectorAll(".menu a");
}
init() {
for (let i = 0; i < this.target.length; i++) {
this.handleClick(i);
}
}
handleClick(index) {
this.target[index].addEventListener('mouseenter', (event) => {
event.preventDefault();
TweenMax.to(this.rule, 0.2, {cssrule:{x: '+10px'}});
});
}
}
let Animate = new animate();
Animate.init();
Keeps saying can not Tween null object. What am I doing wrong?
CSSRulePlugin.getRule doesn't seem to return an Array
var rule = CSSRulePlugin.getRule(".box:after");
TweenLite.to(rule, 1, {cssRule:{backgroundColor:"#600", color:"white"}});
So, you probably need to change your code:
handleClick(index) {
this
.target[index]
.addEventListener('mouseenter', (event) => {
event.preventDefault();
let self = this;
TweenMax.to(self.rule, 0.2, {
cssrule:{x: '+10px'}
});
});
}
ps: you don't need var self = this because arrow function inherit the this.
Why don't you use add remove classes? you can build your animation in css and just add or remove a class at the right moment...

Alternative array navigation hack in AS3 not running as defined :(

for some reasons, this code does not want to work; its supposed to be a convenient alternative to using "arrays" for navigation buttons whereby the clicking of one button removes the click state from the rest -
nav_mc.buttonMode=true;
nav_mc.addEventListener(MouseEvent.MOUSE_OVER, navOver);
nav_mc.addEventListener(MouseEvent.MOUSE_OUT, navOut);
nav_mc.addEventListener(MouseEvent.CLICK, navClick);
nav_mc.nav1_mc.mouseChildren=false;
nav_mc.nav2_mc.mouseChildren=false;
nav_mc.nav3_mc.mouseChildren=false;
nav_mc.nav4_mc.mouseChildren=false;
var currentNav:MovieClip;
function navOver(e:MouseEvent):void {
var navItem:MovieClip=e.target as MovieClip;
trace(navItem.name);
if (navItem!=currentNav) {
navItem.gotoAndStop(2);
}
}
function navOut(e:MouseEvent):void {
var navItem:MovieClip=e.target as MovieClip;
if (navItem!=currentNav) {
navItem.gotoAndStop(1);
}
}
function navClick(e:MouseEvent):void {
var navItem:MovieClip=e.target as MovieClip;
if (currentNav!=null) {
navItem.gotoAndStop(1);
}
currentNav=navItem;
navItem.gotoAndStop(3);
}
please, been on this for hours now, what am I missing out?
My guess is: you should change the navItem variable to the currentNav, inside of the if block here:
if (currentNav!=null) {
navItem.gotoAndStop(1);
}
It looks like you want to make some changes to the current active item (currentNav).
UPD.: My advice is: try to change the code above to the next code
if (currentNav!=null) {
currentNav.gotoAndStop(1);
}
UPD 18-11-2015, Toggle buttons:
It's hard to say if my code works or not (I don't have the whole project to test it), but it looks like it should.
function navClick(e:MouseEvent):void
{
var navItem:MovieClip=e.target as MovieClip;
if (currentNav != null)
{
currentNav.gotoAndStop(1);
}
if(currentNav == navItem)
{
currentNav = null;
}else
{
currentNav = navItem;
navItem.gotoAndStop(3);
}
}

html color to alternative rows of dynamic table

I have a Dynamic table that I want to give color to on alternative rows. How can I achieve this with css? I need the code to work in IE7+
Look into using even/odd rules in CSS3.
Reference: https://developer.mozilla.org/en/CSS/:nth-child
For instance,
tr:nth-child(odd) will represent the CSS for every 2n + 1 child, whereas tr:nth-child(even) will represent the CSS for every 2n child.
i came across this same problem Friday, i used the jquery solution of
$("tr:even").css("background-color", "#CCC");
$("tr:odd").css("background-color", "#FFF");
a stack overflow solution .js posted here
Detect changes in the DOM
so essentially you add the .js script in the head and fire the jquery rules on dom change.
My finished .js looked like this
<script type="text/javascript">
(function (window) {
var last = +new Date();
var delay = 100; // default delay
// Manage event queue
var stack = [];
function callback() {
var now = +new Date();
if (now - last > delay) {
for (var i = 0; i < stack.length; i++) {
stack[i]();
}
last = now;
}
}
// Public interface
var onDomChange = function (fn, newdelay) {
if (newdelay)
delay = newdelay;
stack.push(fn);
};
// Naive approach for compatibility
function naive() {
var last = document.getElementsByTagName('*');
var lastlen = last.length;
var timer = setTimeout(function check() {
// get current state of the document
var current = document.getElementsByTagName('*');
var len = current.length;
// if the length is different
// it's fairly obvious
if (len != lastlen) {
// just make sure the loop finishes early
last = [];
}
// go check every element in order
for (var i = 0; i < len; i++) {
if (current[i] !== last[i]) {
callback();
last = current;
lastlen = len;
break;
}
}
// over, and over, and over again
setTimeout(check, delay);
}, delay);
}
//
// Check for mutation events support
//
var support = {};
var el = document.documentElement;
var remain = 3;
// callback for the tests
function decide() {
if (support.DOMNodeInserted) {
window.addEventListener("DOMContentLoaded", function () {
if (support.DOMSubtreeModified) { // for FF 3+, Chrome
el.addEventListener('DOMSubtreeModified', callback, false);
} else { // for FF 2, Safari, Opera 9.6+
el.addEventListener('DOMNodeInserted', callback, false);
el.addEventListener('DOMNodeRemoved', callback, false);
}
}, false);
} else if (document.onpropertychange) { // for IE 5.5+
document.onpropertychange = callback;
} else { // fallback
naive();
}
}
// checks a particular event
function test(event) {
el.addEventListener(event, function fn() {
support[event] = true;
el.removeEventListener(event, fn, false);
if (--remain === 0) decide();
}, false);
}
// attach test events
if (window.addEventListener) {
test('DOMSubtreeModified');
test('DOMNodeInserted');
test('DOMNodeRemoved');
} else {
decide();
}
// do the dummy test
var dummy = document.createElement("div");
el.appendChild(dummy);
el.removeChild(dummy);
// expose
window.onDomChange = onDomChange;
})(window);
$(document).ready(function () {
$("tr:even").css("background-color", "#CCC");
$("tr:odd").css("background-color", "#FFF");
onDomChange(function () {
$("tr:even").css("background-color", "#CCC");
$("tr:odd").css("background-color", "#FFF");
});
});
</script>
I would like to caveat this answer that this probably is not the greatest solution but worked for what i needed it to do. :-)
CSS3 nth-child selector:
tr:nth-child(odd) {
background: red /* or whatever */;
}
You can use a CSS3 selector:
tr:nth-child(even) {background: #CCC}
tr:nth-child(odd) {background: #FFF}
or jQuery:
$("tr:even").css("background-color", "#CCC");
$("tr:odd").css("background-color", "#FFF");
or do it on the server side.