I'm trying to make my input field have a black background and white text, but I can't find any documentation for the possible values input.style() can take. I'm currently trying:
input.style('background-color', "#121212", 'color', "#EEE")
The background color works, but the text color doesn't. I followed the same syntax the reference uses so I'm not sure why.
Also if anyone could point me to where in the documentation it lists all the possible arguments for .style() it'd be much appreciated.
The p5 style() function takes only two arguments: the property name and the value. You are trying to set additional properties by adding more arguments, which you cannot do. You need to break this up into two lines and set each property individually.
input.style('background-color', "#121212")
input.style('color', "#EEE")
Try using two separate calls to .style, one for each property you want to set:
function setup() {
noCanvas();
const inp = createElement("input");
inp.value("hello world");
inp.style("background", "yellow");
inp.style("color", "green");
// or chained:
inp
.style("background", "yellow")
.style("color", "green");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.5.0/p5.js"></script>
I prefer to style with classes and a CSS stylesheet, separating presentation and behavior and making it easier to apply the style to many elements without writing a ton of repetitive JS:
function setup() {
noCanvas();
const inp = createElement("input");
inp.class("ugly");
inp.value("hello world");
}
.ugly {
background-color: yellow;
color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.5.0/p5.js"></script>
Note also, with respect to naming an input input:
p5.js says: you have used a p5.js reserved function "input" make sure you change the function name to something else.
Related
I ask participants yes/no questions in an experiment and they answer by keypress (Y/N). Now, I want to display YES green and NO red.
I'm doing this with Ibex farms where you have an experiment file in .js format. In this file, one defines the "Question controller" as follows:
"Question", {
as: [["Y","Yes"],["N","No"]], //defines keys+answer displays
}
Adding html tags <font-size>, <div style> in this line did not work.
Besides that, there is a .css file in which I can change the color for both answers, but give the same color to both:
span.Question-fake-link {
color: #ff6600; //changing this to red; both Yes and No are red now
cursor: pointer;
}
The third file is a Question.js file which defines behavior and properties of the question controller beyond its appearance. It is too long to post here, I think, and I don't have authorship. But in there, the answers are defined as "left Comment" and "right Comment". So I attempted to add the 4th line at the (I hope) relevant place:
var lcd = $(document.createElement("li"))
.addClass(this.cssPrefix + "scale-comment-box")
.append(this.leftComment);
.document.getElementById("leftComment").style.color = "red"; //added this, made experiment dysfunctional
this.xl.append(lcd);
Does anyone know how to change the colours individually?
I'm sorry, I know this must look complicated, but maybe someone can give me a pointer on what to do...If you need more of the scripts, please let me know.
Many thanks.
EDIT: After trying out some of the suggestions here, I see the answers are somehow as "span.fake-link". Maybe this code snippet can help (line 1/2):
var a = $(document.createElement("span")).addClass(this.cssPrefix + "fake-link");
__Question_answers__[i] = ans;
__Question_callback__ = function (i) {
var answerTime = new Date().getTime();
var ans = __Question_answers__[i];
var correct = "NULL";
if (! (t.hasCorrect === false)) {...}
}
But how can I replace "span" or "fake-link"? I guess I have to replace both. Removing the span.fake-link properties in css-files doesn't seem to help.
EDIT: Or could this be the problem?
if ((this.presentAsScale || this.presentHorizontally) && this.leftComment) {
var lcd = $(document.createElement("li"))
.addClass(this.cssPrefix + "scale-comment-box")
.append(this.leftComment)
.appendTo(this.xl)
this.xl.append(lcd);
}
I attempted to replace "scale-comment-box" by "red" (defined as a class in css before), but that also doesn't help.
You could probably use jquerys css function:
$("<li>")
.addClass(this.cssPrefix + "scale-comment-box")
.css({color:"red"})
.append(this.leftComment)
.appendTo(this.xl);
Since you're already using Javascript, is it feasible for you to add two extra css classes?
One could be .red and the other, .green and then append those classes to the element accordingly at creation:
//CSS
.red{
color:#F00;
}
.green{
color:#0F0;
}
//javascript
//Your javascript seems to be a mix of jQuery and JS so I assume jQuery is imported. If this is incorrect, you would need to use a raw javascript solution
//Hint: Look at document.getElementsByClassName and .classname += "red"
//jQuery version:
$("li").addClass("red") //for any items that need to be red. replace red with green for the green items
I'm trying to simulate an Etch-a-Sketch and I want to let the user change the squares color using the [type=color] input. Until now I was only painting them black...
I've tried assigning a variable to the color hex code obtained from the form and creating unique classes using that value as class name, which seems ok, but then I cannot edit the css "background-value" for that class, since from what I've read, you can't edit variables' css.
Any help is appreciated.
The hover-color-applying javascript part is as follows:
//apply hover effect
$(document).on("mouseenter", ".gridSlot", function() {
var color = document.getElementById("myColor").value; //myColor = input
$(this).addClass(color); //what I want to do
$(this).addClass("color"); //what I'm doing
});
.color is a class with a fixed background-color, and if I change it by using $(".color").css("background-color"), it'll change both old and new squares colors.
Is there a way to let the already hovered ones be, for example, black, and draw new red ones?
JSFiddle: https://jsfiddle.net/0g3c6c0v/1/
Simply use .css Reference jQuery.css
Add a non existing class name to it to check if the square is already painted.
$(document).on("mouseenter", ".gridSlot", function() {
var color = document.getElementById("myColor").value;
if(!$(this).hasClass("painted")){
$(this).css("background-color",color);
$(this).addClass("painted");
}
});
Updated Fiddle
This might be a good place to use a global variable. At the top of your JS add line like this: window.color_picker = "#000000";
And then in your function simply use: $(this).css("background-color",window.color_picker);
Anytime that the color picker changes you'll need a js function that updates that global:
$('#myColor').on("change", function() {
window.color_picker = $('#myColor').val();
});
I'm trying to change an entire svg by changing the class.The problem is that I don't know for sure how to set a new class to the svg so I tried like this:
<script>
function change() {
document.getElementById("hi").setAttribute("className", "Hi Hello")
}
</script>
Fiddle here:https://jsfiddle.net/orhojkq6/1/
Can someone please tell me if I am wrong somewhere?I am an beginner.
That is a very strange method being used to modify the svg background, but if you want to add a class name to the svg, the easiest method would be to use classList
window.onload = function() {
setTimeout(function() {
document.getElementById("hi").classList.add("Hello");
}, 2000);
}
I wouldn't recommend using inline javascript, so I removed it in this demo.
Also, it isn't conventional to use capital letters at the start of a class name.
Is it somehow possible to parameterize the jQuery addClass() method?
Like, having a css class with a color property which is set when the addClass() method is called?
I hope that makes sense as I am very new to JavaScript and CSS. If it's of importance, I'm working on extending the MediaWiki VisualEditor. There this method is used to immediatly show/render changes made in the editor. But I couldn't find an example which would require parameterization.
If it's not possible, I'd love to know how to do it.
If it's not, maybe someone can suggest how to realize what I want another way?
Edit:
That's the current state:
When I add some annotation to the text, let's say a languageAnnotation, this is called:
this.$element
.addClass( 've-ce-languageAnnotation' )
.addClass( 've-ce-bidi-isolate' )
.prop( {
lang: this.model.getAttribute( 'lang' ),
dir: this.model.getAttribute( 'dir' ),
title: this.constructor.static.getDescription( this.model )
} );
This is ve-ce-languageAnnotation:
.ve-ce-languageAnnotation {
border-bottom: 1px dashed #ccc;
background-color: #ebf3f5;
}
This is ve-ce-bidi-isolate:
.ve-ce-bidi-isolate {
unicode-bidi: isolate;
unicode-bidi: -moz-isolate;
unicode-bidi: -webkit-isolate;
}
I interpreted this as the prop() function setting some kind of parameter. So this is what I tried for my textColor annotation:
this.$element
.addClass( 've-ce-textColorAnnotation' )
.prop( {
color: this.model.getAttribute( 'style' ),
title: this.constructor.static.getDescription( this.model )
} )
;
With ve-ce-TextColorAnnotation:
.ve-ce-textColorAnnotation {
color: red;
}
This always produces red. When I try to enter something else then a legit color, nothing happens.
Edit2: I guess one option would be to create a class for each possible color, and adding the right class depending on the parameter? Like this:
var color = this.model.getAttribute('style');
if (color == 'blue') {
this.$element.addClass( 'blueText' )
} else if (...
but that doesn't look like a really good idea.
Edit 3: According to the top answer in this question, what I want is not possible - but I can directly apply an attribute without using classes by using this.$element.css('attr', 'value'). I guess I can use this for what I need.
It appears you simply want to set a color, rather than add a class. Classes in HTML can be used for stylization or DOM navigation, however in your case you simply want to apply a different color to an element. You don't need to use classes for that, especially if the colors are dynamic.
What you want to do is call jquery's .css() method. It can be used with a single argument like so:
element.css({
'color': 'black',
'height': '100px'
});
or several, if you only want to edit a single property:
element.css('color', 'black');
Without using jQuery, you could also do this:
element.style.color = 'black';
What can you do in a simple way. Let's say you have a drop down from which you chose the colors. On the value attribute of the option you have blueText for blue, redText for red and so on for each color you want.
Then on the code you can get the value. You can see here how to get the value then you have the classes in CSS like redText, blueText and so on.
When the user clicks on the option you catch the event and do this simple pice of code:
this.$element.addClass( 'text that you got from value attribute' )
You can of course remove the classes before you do the add.
I'd like to:
Find a style attribute for all elements in the page (for instance: all elements that have color:#333;)
Change this attribute for all of them (for instance from color:#333 to color:#444).
Do you have any suggestion on doing so?
My suggestion is avoid doing this if at all remotely possible. Instead, use a class to assign the color value, and then you can look up the elements using the class, rather than the color value.
As far as I'm aware, there's no selector (not even in CSS3) that you can use to query a specific style value, which means looping through all elements (or it looks like you can restrict it to all elements with a style attribute) and looking at the element.style.color property. Now, the thing is, even though you write color: #333; in your style attribute, different browsers will echo it back to you in different ways. It might be #333, it might be #333333, it might be rgb(51, 51, 51), it might even be rgba(51, 51, 51, 0).
So on the whole, a very awkward exercise indeed.
Since you've said this is for a Chrome extension, you probably don't have to worry as much about multiple formats, although I'd throw in the ones that we've seen in the wild in case Chrome changes the format (perhaps to be consistent with some other browser, which has been known to happen).
But for instance:
(function() {
// Get all elements that have a style attribute
var elms = document.querySelectorAll("*[style]");
// Loop through them
Array.prototype.forEach.call(elms, function(elm) {
// Get the color value
var clr = elm.style.color || "";
// Remove all whitespace, make it all lower case
clr = clr.replace(/\s/g, "").toLowerCase();
// Switch on the possible values we know of
switch (clr) {
case "#333":
case "#333333":
case "rgb(51,51,51)": // <=== This is the one Chrome seems to use
case "rgba(51,51,51,0)":
elm.style.color = "#444";
break;
}
});
})();
Live example using red for clarity | source - Note that the example relies on ES5 features and querySelectorAll, but as this is Chrome, I know they're there.
Note that the above assumes inline style, because you talked about the style attribute. If you mean computed style, then there's nothing for it but to loop through all elements on the page calling getComputedStyle. Other than that, the above applies.
Final note: If you really meant a style attribute with precisely the value color: #333 and not the value color:#333 or color:#333333; or color: #333; font-weight: bold or any other string, your querySelectorAll could handle that: querySelectorAll('*[style="color: #333"]'). But it would be very fragile.
From your comment below, it sounds like you're having to go through every element. If so, I wouldn't use querySelectorAll at all, I'd use recursive descent:
function walk(elm) {
var node;
// ...handle this element's `style` or `getComputedStyle`...
// Handle child elements
for (node = elm.firstChild; node; node = node.nextSibling) {
if (node.nodeType === 1) { // 1 == Element
walk(node);
}
}
}
// Kick it off starting with the `body` element
walk(document.body);
That way you don't build up large, unnecessary temporary structures. This is probably the most efficient way to walk the entire DOM of a document.
It's definitely more simple if you use jquery.
In any case, the best would be to use classes and use the filter jquery method to get the objects you want.
But if you really want to get them you can do something like:
$(function () {
$('p').filter(function () {
return $(this).css('color') == '#333';
}).css('color', '#444');
});
The above script get the elements with the desired css attribute and set a new css attribute (color #444).
You can't, if you don't add at least a specific CSS class to all this elements you want to track.
Or better, you can with very poor performances by looping on all the elements of the DOM until you find what you're looking for. But please, don't think of doing this
It's as already said really hard / inefficient to query all elements by color.
// refrence: http://stackoverflow.com/questions/5999209/jquery-how-to-get-the-background-color-code-of-an-element
var arr = [];
$('*').each(function (i, ele) {
// is red => save
if($(ele).css('backgroundColor') == ('rgb(0, 0, 255)')) arr.push(ele);
});
console.log(arr);
Here is an JSFiddle Example for it: http://jsfiddle.net/ddAg7/
My recommendation for this is: Don't do it!
Something like
$('selector').each(function() {
if($(this).attr('style').indexOf('font-weight') > -1) {
alert('got my attribute');
}
});
in the if statement you could replace it with a different css... Not sure.. haven't tried on all browsers though :)
oneliner
[...document.querySelectorAll("[style*='color:#333']")].forEach(e=>e.style.color='#444')
function switchColors() {
[...document.querySelectorAll("div[style*='color:#333']")]
.forEach(el => el.style.color = '#f00')
}
<div>EXAMPLE:
<div>
<div style="background: #eee; color:#333;">aaa</div>
<div style="background: gray; color:#00f;">
bbb
<div style="color:#333;">ccc</div>
</div>
</div>
<div style="color:#040;">ddd</div>
<div style="color:#333; font-size: 20px">eee</div>
</div>
<button onclick="switchColors()">Switch Colors</button>