Generating the same 2 random colors for 2 different objects - html

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.

Related

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.

Set HTML Background Color as JS Variable

I want to set a variable that's been set in JavaScript as an HTML page's background.
I'm making a Chrome new tab override, and part of it is generating a random colour hex to be the background.
After getting this problem, I decided to test it out:
<body style="background-color:colour;">
<script>
var colour = blue;
</script>
</body>
And yes, the tags are there. I had to delete them because stackoverflow doesn't let them show.
You can use JavaScript to set the background color instead of trying to use a JavaScript variable in the HTML, as that is not possible:
var colour = "blue";
document.body.style.backgroundColor = colour;
You can follow the below practice to randomly change background-color of any element.
<body id="bodyTag">
<script>
function getColor() {
let codes = 'abcdef0123456789';
var color = '#';
for (var i = 0; i < 6; i++) {
color += codes[Math.floor(Math.random() * 16)];
}
return color;
}
var body = document.getElementById("bodyTag");
body.style.background=getColor();
</script>
</body>

Extending native HTML element in Angular 6

I have recently created a native web component which is working well in all browsers. I moved this web component into an Angular 6 application and all works as expected. I then tried to extend a native HTML element which again worked perfectly except when I brought it into my Angular 6 application.
Using the examples from Mozilla I will try and illustrate my issue. Using the following trying to extend a native 'p' element:
// Create a class for the element
class WordCount extends HTMLParagraphElement {
constructor() {
// Always call super first in constructor
super();
// count words in element's parent element
var wcParent = this.parentNode;
function countWords(node){
var text = node.innerText || node.textContent
return text.split(/\s+/g).length;
}
var count = 'Words: ' + countWords(wcParent);
// Create a shadow root
var shadow = this.attachShadow({mode: 'open'});
// Create text node and add word count to it
var text = document.createElement('span');
text.textContent = count;
// Append it to the shadow root
shadow.appendChild(text);
// Update count when element content changes
setInterval(function() {
var count = 'Words: ' + countWords(wcParent);
text.textContent = count;
}, 200)
}
}
// Define the new element
customElements.define('word-count', WordCount, { extends: 'p' });
<p is="word-count">This is some text</p>
By taking that same code and putting it into an Angular 6 application, the component never runs. I put console log statements in the constructor and connectedCallback methods and they never trigger. If I remove the {extends: 'p'} object and change the extends HTMLParagraphElement and make it an extend HTMLElement to be an autonomous custom element everything works beautifully. Am I doing something wrong or does Angular 6 not support the customized built-in element extension?
I assume the reason is the way that Angular creates those customized built-in elements when parsing component templates - it probably does not know how to properly do that. Odds are it considers is a regular attribute which is fine to add after creation of the element (which it isn't).
First creating the element and then adding the is-attribute will unfortunately not upgrade the element.
See below example: div#d has a non-working example of that customized input.
customElements.define('my-input', class extends HTMLInputElement {
connectedCallback() {
this.value = this.parentNode.id
this.parentNode.classList.add('connected')
}
}, {
extends: 'input'
})
document.addEventListener('DOMContentLoaded', () => {
b.innerHTML = `<input type="text" is="my-input">`
let el = document.createElement('input', {
is: 'my-input'
})
el.type = 'text'
c.appendChild(el)
// will not work:
let el2 = document.createElement('input')
el2.setAttribute('is', 'my-input')
el2.type = 'text'
d.appendChild(el2)
})
div {
border: 3px dotted #999;
padding: 10px;
}
div::before {
content: "#"attr(id)" ";
}
.connected {
background-color: lime;
}
<div id="a"><input type="text" is="my-input"></div>
<div id="b"></div>
<div id="c"></div>
<div id="d"></div>
So to get it to work with Angular, hook into the lifecycle of your Angular component (e.g. onInit() callback) and pick a working way to create your element there.

AS3 Passing Variable Parameters to a generic Function Menu / SubItems

I'm no code genius, but a fan of action script.
Can you help me on this:
I have a function that depending on the object selected, will call event listeners to a set of 'sub-items' that are already on stage (I want to reuse this subitems with changed parameters upon click, instead of creating several instances and several code).
So for each selected 'case' I have to pass diferent variables to those 'sub-items', like this:
function fooMenu(event:MouseEvent):void {
switch (event.currentTarget.name)
{
case "btUa1" :
trace(event.currentTarget.name);
// a bunch of code goes here
//(just cleaned to easy the view)
/*
HELP HERE <--
here is a way to pass the variables to those subitems
*/
break;
}
}
function fooSub(event:MouseEvent):void
{
trace(event.target.data);
trace(event.currentTarget.name);
// HELP PLEASE <-> How can I access the variables that I need here ?
}
btUa1.addEventListener(MouseEvent.CLICK, fooMenu);
btUa2.addEventListener(MouseEvent.CLICK, fooMenu);
btTextos.addEventListener(MouseEvent.CLICK, fooSub);
btLegislacao.addEventListener(MouseEvent.CLICK, fooSub);
Anyone to help me please?
Thank very much in advance. :)
(I'm not sure I got your question right, and I haven't developed in AS3 for a while.)
If you want to simply create function with parameters which will be called upon a click (or other event) you can simply use this:
btUa1.addEventListener(MouseEvent.CLICK, function() {
fooMenu(parameters);
});
btUa2.addEventListener(MouseEvent.CLICK, function() {
fooMenu(other_parameters)
}):
public function fooMenu(...rest):void {
for(var i:uint = 0; i < rest.length; i++)
{
// creating elements
}
}
If you want to call event listeners assigned to something else you can use DispatchEvent
btnTextos.dispatchEvent(new MouseEvent(MouseEvent.CLICK))
Remember, you can't use btTextos.addEventListener(MouseEvent.CLICK, carregaConteudo("jocasta")); because the 2nd parameter you pass while adding Eventlistener will be considered as function itself - there are two proper ways to use addEventListener:
1:
function doSomething(event:MouseEvent):void
{
// function code
}
element.addEventListener(MouseEvent.CLICK, doSomething); //notice no brackets
2:
element.addEventListener(MouseEvent.CLICK, function() { // function code });
So:
function fooSub(event:MouseEvent, bla:String):void
{
trace(event.currentTarget.name+" - "+bla);
// bla would be a clip name.
}
codebtTextos.addEventListener(MouseEvent.CLICK, function(e:MouseEvent) { fooSub(e, "jocasta") } );
Or try something like this if you want content to be dynamically generated:
btUa1.addEventListener(MouseEvent.CLICK, function() {
createMenu(1);
});
btUa2.addEventListener(MouseEvent.CLICK, function() {
createMenu(2);
});
function createMenu(id):void
{
// Switching submenu elements
switch (id)
{
case 1:
createSubmenu([myFunc1, myFunc2, myFunc3]); // dynamically creating submenus in case you need more of them than u already have
break;
case 2:
createSubmenu([myFunc4, myFunc5, myFunc6, myFunc7]);
break;
default:
[ and so on ..]
}
}
function createSubmenu(...rest):void {
for (var i:uint = 0; i < rest.length; i++)
{
var mc:SubItem = new SubItem(); // Subitem should be an MovieClip in library exported for ActionScript
mc.addEventListener(MouseEvent.CLICK, rest[i] as function)
mc.x = i * 100;
mc.y = 0;
this.addChild(mc);
}
}
Your question is rather vague; what "variables" do you want to "pass"? And what do you mean by "passing the variable to a sub item"? Usually "passing" means invoking a function.
If you can be more specific on what exactly your trying to do that would be helpful. In the meantime, here are three things that may get at what you want:
You can get any member of any object using bracket notation.
var mc:MovieClip = someMovieClip;
var xVal:Number = mc.x; // The obvious way
xVal = mc["x"]; // This works too
var propName:String = "x";
xVal = mc[propName] ; // So does this.
You can refer to functions using variables
function echo(message:String):void {
trace(message);
}
echo("Hello"); // The normal way
var f:Function = echo;
f("Hello"); // This also works
You can call a function with all the arguments in an array using function.apply
// Extending the above example...
var fArgs:Array = ["Hello"];
f.apply(fArgs); // This does the same thing
Between these three things (and the rest parameter noted by another poster) you can write some very flexible code. Dynamic code comes at a performance cost for sure, but as long as the frequency of calls is a few hundred times per second or less you'll never notice the difference.

How to randomly assign a color on hover effect

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 () {
});
}