This question already has answers here:
How to compare colors in JavaScript?
(6 answers)
Closed 5 years ago.
I have made a DIV that changes color, but I'm trying to find a way to know when it turns red. Here's what I need it to do:
if (DIV BACKGROUND COLOR RED) {
alert("DIV IS RED");
}
How would I accomplish this?
Yes can do this by using attribute change jquery plugin...
As I can see you want an event to be triggered on color change automatically... So, your code will be something like this with its working example...
$("#myDiv").attrchange({
trackValues: true,
// set to true so that the event object is updated with old & new values
callback: function(evnt) {
if(evnt.newValue.indexOf('background: red') > -1) {
// which attribute you want to watch for changes
alert("DIV IS RED");
}
}
});
function change(x){
document.getElementById("myDiv").style.background=x;
}
#myDiv{
background:green;
}
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://cdn.rawgit.com/meetselva/attrchange/master/js/attrchange.js"></script>
<script src="https://cdn.rawgit.com/meetselva/attrchange/master/js/attrchange_ext.js"></script>
<div id="myDiv">This Div Changes colors</div>
<button onclick="change('red');">Change To Red</button>
<button onclick="change('blue');">Change To Blue</button>
<button onclick="change('green');">Change To Green</button>
The above code will prompt a message when the div turns red...
You can access an element's background colour via window.getComputedStyle(element).backgroundColor.
This will be a string in either "rgb" or "rgba" representation, e.g.:
rgb(127, 127, 127)
rgba(127, 127, 127, 1)
An element is "red" if it's red component (the 1st number) is greater than the other colour components. Both rgb and rgba have 3 color components, and rgba has an extra "alpha" (transparency) component - which we can ignore, because it doesn't affect "redness".
We'll get the red green and blue components of the element's background color, and consider the element "red" if its red color component is greater than the green and blue components:
var isRed = function(element) {
var bg = window.getComputedStyle(element).backgroundColor;
if (!bg) return false; // Sometimes there is no background color, in which case the element isn't red
// Otherwise, `bg` is a string:
var rb = bg.indexOf('(');
bg = bg.substr(rb + 1); // Trim off everything up until and including the "(" character
bg = bg.split(','); // Split on the "," delimiter
var r = parseInt(bg[0].trim());
var g = parseInt(bg[1].trim());
var b = parseInt(bg[2].trim());
return r > g && r > b;
};
console.log('#red?', isRed(document.getElementById('red')));
console.log('#green?', isRed(document.getElementById('green')));
console.log('#blue?', isRed(document.getElementById('blue')));
console.log('#quiteRed?', isRed(document.getElementById('quiteRed')));
console.log('#notRed?', isRed(document.getElementById('notRed')));
console.log('#transparentRed?', isRed(document.getElementById('transparentRed')));
.col {
width: 100%;
height: 30px;
color: #ffffff;
line-height: 30px;
}
#red { background-color: #ff0000; }
#green { background-color: #00ff00; }
#blue { background-color: #0000ff; }
#quiteRed { background-color: rgb(220, 130, 120); }
#notRed { background-color: #80b0c0; }
#transparentRed { background-color: rgba(200, 50, 50, 0.4); }
<div class="col" id="red">red</div>
<div class="col" id="green">green</div>
<div class="col" id="blue">blue</div>
<div class="col" id="quiteRed">quiteRed</div>
<div class="col" id="notRed">notRed</div>
<div class="col" id="transparentRed">transparentRed</div>
Related
I want to change the view of an object from a JS function depending on any events.
For example, I have a set of forms, including an input form of type text. While it is not completely filled, the color of the frame and font is green, when it is completely filled - red.
At the same time, I want to keep the freedom of the HTML designer and give him the opportunity to set class names arbitrarily. I want to operate at the subclass level.
I set this:
.info.available {
color: green;
border: 1px solid lime;
}
.info.full {
color: red;
border: 1px solid red;
}
And
<input class="info available" type="text" id="info">
I have a function myfunc(obj) that takes a pointer "this" and works with different components of a formset.
How for obj.form.info ... to switch the subclass from "available" to "full" and vice versa? How can I get its current value?
first, specify an input maxlength to know if its is completely filled or not.
<input class="info available" max-length="10" type="text" id="input">
then remove the outline color from your input field when it is clicked or being typed
input.available {
border: 1px solid green;
}
input.full {
border: 1px solid red;
}
input:focus {
outline: none;
}
this is to make .available and .full classes visible. then add an action event to your input field that will listen for every string that is typed. you can do it by:
next in your script tag, create the function that will be fired from your input field
<script>
function myfunc(e) {
let x = document.getElementById('input')
if (x.value.length == 10)
{
x.classList.remove('available')
x.classList.add('full')
}
else {
x.classList.add('available')
x.classList.remove('full')
}
}
</script>
x refers to your input field
x.value.length refers to the length of characters that is in your input field
if x.value.length is equal to your input's maxlength(which we specified as 10), it will replace the class .available by .full and vice versa
you can read the documentation or tutorials here:
https://www.w3schools.com/js/js_events.asp
https://www.w3schools.com/tags/ref_eventattributes.asp
Use maxlength="{maxlen}" for your input.
function myfunc(obj) {
if (obj.value.length >= maxlen) {
obj.classList.remove('available');
obj.classList.add('full');
} else {
obj.classList.add('available');
obj.classList.remove('full');
}
}
I have multiple elements with the class .hours and they all have a color attribute with a hex value like so: <div class="hours" color="#FFFFFF">.
How can I use jQuery to set the background color of all the elements individually so that the element over has the color #FFFFFF and the element <div class="hours" color="#666666"> gets the background color #666666?
My attempt: $('.hours').css('background-color', this.attr.color);
You can use .each to refer to every element and it's color attribute
$('.hours').each(function() {
let elem = $(this);
elem.css('background', elem.attr('color'));
});
.hours {
border: 1px solid black;
height: 100px;
width: 100px;
display: inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="hours" color="#FFFFFF"></div>
<div class="hours" color="#AAAAAA"></div>
<div class="hours" color="#444444"></div>
Pure JS solution (for this jQuery is rather ineffective in my opinion...):
document.querySelectorAll('.hours').forEach(function(el) {
el.style.backgroundColor = el.getAttribute('color');
});
try with this
$('.hours').each(function(){
var t = $(this);
t.css('background-color', t.attr('color'));
});
})
$(".hours").each(function(){
let $this= $(this);
let color=$this.attr("color");
$this.css("background-color", color);
});
Not really what you asked, but the same can be achieved without JS, just with pure CSS and custom properties:
<div style="--color: green"></div>
div {
--color: #e2001a; /* default color */
background-color: var(--color);
height: 40px;
}
Example: http://jsfiddle.net/e1fwtcdz/1
How do I stop the cursor changing location when innerHTML is edited by javascript?
I am currently making a little code editor project where I want text highlighting, but to do that I must edit the innerHTML / DOM element to add a span into it. But when that happens it changes location to start of text.
var c = document.getElementById("c");
var t = setInterval(function(){
c.innerHTML = $("#c").text().split("lol").join("<span class='hi1'>lol</span>");
},1);
[contenteditable] {
border: 1px solid gray;
}
.hi1 {
color: rgb(51, 153, 255);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div contenteditable id="c">
write "l o l" without spaces. Then continue to write and try to change location with arrow keys / mouse
</div>
I am working on a project that will get background color from two different divs using two different onClick events.My Divs have hex background color values. I want to get them and concatenate them as a linear gradient, apply them to a parent div and also want to convert the same code to rgb.
Here is my HTML,CSS and Js
<div class="color ForeignCrismon" onClick="GetColorOne(event)"></div> <!--First Color Stop-->
<div class="color BrewedBrown" onClick="GetColorTwo(event)"></div> <!--Second Color Stop-->
Background Color of these two divs in Css
.ForeignCrismon {background-color:#C91F37;} /* Div 1 color */
.BrewedBrown {background-color:#E68364;} /* Div 2 color */
Can anyone suggest me Javascript for this?
Thank you very much.
Here is a Solution,
Hopes, it will help you!
HTML:
<div class="color ForeignCrismon" onClick="GetColorOne(event)"></div>
<!--First Color Stop-->
<div class="color BrewedBrown" onClick="GetColorTwo(event)"></div>
<!--Second Color Stop-->
<div id="ParentBox"></div>
CSS:
.color {
width: 100px;
height: 100px;
margin: 30px;
}
.ForeignCrismon {background-color:#C91F37;} /* Div 1 color */
.BrewedBrown {background-color:#E68364;} /* Div 2 color */
#ParentBox {
width: 500px;
height: 200px;
background: linear-gradient(red, blue);
margin: 30px;
}
JS:
var FirstColor, SecondColor;
function GetColorOne(e) {
var ColorBox = e.target;
style = window.getComputedStyle(ColorBox),
BgColor = style.getPropertyValue('background-color');
FirstColor = BgColor;
}
function GetColorTwo(e) {
var ColorBox = e.target;
style = window.getComputedStyle(ColorBox),
BgColor = style.getPropertyValue('background-color');
SecondColor = BgColor;
}
function ApplyGradient() {
if(FirstColor && SecondColor) {
var parent = document.getElementById("ParentBox");
parent.style.background = 'linear-gradient(' + FirstColor + ',' + SecondColor + ')';
}
}
document.addEventListener("click", ApplyGradient);
I am wondering how to search specific string in big textbox (which contains 200 words) so I can make function to color them. Ex. In textbox there is a sentence "my dog is happy" and i want string "dog" to become red by button or sth else. Is it possible???
Yes, it is possible. But don't use a text box or text area, use a div with contenteditable = "true":
<div id="editableDiv" class="editable" contenteditable="true">
This is a sentence containing 'dog'.<br />
You can edit the contents of this div.
</div>
<button id="highlightBtn">Highlight "dog"</button>
<script type="text/javascript">
highlightBtn.onclick = function() {
var elem = document.getElementById('editableDiv');
elem.innerHTML = elem.innerHTML.replace(/dog/g,
'<span class="redText">dog</span>');
}
</script>
And don't forget to create the classes redText and editable in your stylesheet:
.editable {
padding: 5px;
border: dashed 1px black;
}
.redText {
color: red;
}
JSFiddle: http://jsfiddle.net/ProgramFOX/UMMPh/