Checking color value in javascript - javascript

So I set the color of the <body> with:
body
{
color:Black;
}
within the <head> and <style> tags,
and then I've got various elements in the body, for which if I click them, they call a function. i.e.
<p id="CSE1020" onclick="prereq(this)">CSE1020</p>
The prereq function is as follows:
function prereq(code) {
if (code.style.color != "black") {
code.style.color = "black";
code.style.fontWeight = "normal";
}
}
And otherwise, if the element is already black, I change the color.
The problem/question is: I have to click the element twice before it changes color.
In other words, its not 'black' initially. The if statement is executed, even though the default color, before it is clicked should be black. How do I get it to recognize that when I first click the element, that it's 'black'?

Is jQuery an option? If it is you could do this:http://jsfiddle.net/CxayY/
$('#CSE1020').on('click', function(){
if($('body').css('color')!='black')
{
$('body').css('color','black');
$('body').css('font-weight','normal');
}
});

Try searching in CSSRules:
function prereq(code) {
var cssRules = window.getMatchedCSSRules(code);
...
}

So, it works when I add the style to the element itself, i.e.
<p id="CSE1020" style="color:black" onclick="prereq(this)">CSE1020</p>

Related

EventListener Only Firing Once

still learning the basics of JS, working with EventListeners now. Trying to make a button that changes the color of text back and forth but I think I'm misunderstanding the nature of the method, or using it incorrectly. I don't believe it's a syntax issue.
I have the text and the button, both with Id's. I created variables for both elements. I add an event listener to the button, and defined the if else statement in the function. The "if" portion of the function executes without issue, but that's where it ends. Sorry in advance for the formatting I wasn't sure what made the most sense. Thanks!
Here's the HTML:
<h1 id="header"> Here's some text </h1>
<button id="button"> Change the Color </button>
CSS:
#header {
color: red;
}
And the JavaScript:
var header = document.getElementById("header");
var button = document.getElementById("button");
button.addEventListener("click", function() {
if (header.style.color = "red")
{header.style.color = "blue";}
else if (head.style.color = "blue")
{header.style.color = "red";
}
})
In JavaScript (and other languages) you need to use == to check for equality.
However, in JavaScript there is also ===. === is the strict equality operator, meaning it does not do type conversion. What does that mean? It means:
"5" == 5 // true, since "5" as a number is equal to 5, the literal number
"5" === 5 // false, since a string cannot equal a number
So in your if statements you should use == or === instead of just =.
Others have mentioned the use of = vs == vs === - which is definitely your problem, but you're also going to have other problems with comparing styles the way you are doing.
The style property is unique and cumbersome. You have the "style" property which is a property of the DOM node (just like href for anchors or type for inputs). Then you have styles which are applied from a stylesheet - either a <style> tag or external stylesheet file. Sometimes the two different styles sources are in conflict.
For style properties, you read the node.style.color property like you are doing. To get the actual color being applied to the node, you must use window.getComputedStyle(). Let me explain the difference by example:
const div = document.getElementById('foo')
div.style.color; //-> red
window.getComputedStyle(div).color; //-> rbg(0, 255, 0) - this is green!
#foo { color: green !important }
<div id="foo" style="color: red">Hello!</div>
Notice how we set red on the node itself, but green !important in the stylesheet. The !important will win, which is why the text is green. Furthermore, the browser converts the color name green to its RGB equivalent rgb(0, 255, 0). This can be tedious to reconcile. What I usually recommend is having multiple class names and switching between those on click:
var header = document.getElementById("header");
var button = document.getElementById("button");
button.addEventListener("click", function() {
if (header.classList.contains("red")) {
header.classList.remove("red")
header.classList.add("blue")
} else if (header.classList.contains("blue")) {
header.classList.remove("blue")
header.classList.add("red")
}
})
.red { color: red }
.blue { color: blue }
<h1 id="header" class="red"> Here's some text </h1>
<button id="button"> Change the Color </button>

Toggling Background Color on Click with Javascript

I am working on a class project and need to be able to toggle the background color of a transparent png on click. I have been working through a number of examples from the site, but I can't get it working. I am a total novice at Javascript and haven't had luck trying to plug in jQuery code either.
Here is the targeted section:
<div class="expenseIcon"><a href="#">
<img src="images/mortgage.png"></a><br/>
<p>Rent or Mortgage</p>
</div>
On clicking the linked image, the goal is for the background on the image to change to green. Clicking it again would change it back to the default, white. Here's the CSS I'd like to toggle on/off with click.
.colorToggle {
background: #A6D785;
}
I had tried adding class="iconLink" to the href and class="iconBox" to the image with the following Javascript adapted from another post, but it didn't work.
var obj = {};
$(document).ready(function () {
$(".iconLink").click(function () {
var text = $(this).find(".iconBox");
obj.var1 = text;
//alert(obj.var1);
//return false;
$('.iconBox').removeClass('colorToggle');
$(this).addClass('colorToggle')
});
});
Any advice would be greatly appreciated!
Let's break down what is happening with your current code when you click the link.
var obj = {};
$(document).ready(function () {
$(".iconLink").click(function () {
var text = $(this).find(".iconBox");
obj.var1 = text;
$('.iconBox').removeClass('colorToggle');
$(this).addClass('colorToggle')
});
});
JQuery finds all elements with the classname "iconBox". In your case, this is the img element. The reference to that element is then saved in "obj.var1". You do not end up doing anything with this reference, so these two lines can be removed.
All elements with the class "iconBox" have the class "colorToggle" removed. Your img element didn't have this class on it, so nothing happens.
The class "colorToggle" is added to the anchor element. Yes! Now the element wrapping the img has a background color.
Unfortunately, clicking the anchor tag again won't do anything, since the anchor tag will already have the "colorToggle" class and all we would be doing would be trying to add it again. Hmm. Let's try changing addClass to toggleClass. Here's our new code:
$(document).ready(function () {
$(".iconLink").click(function () {
$(this).toggleClass('colorToggle');
}
});
Also, note that because we're working with the anchor element, the p element won't be affected by this change. If you want the entire div to change background colors, use this line instead:
$(".expenseIcon").toggleClass('colorToggle');
Using the given markup:
<!-- to toggle the bg-color onClick of anchor tag -->
<div class="expenseIcon">
<a href="#">
<img src="images/mortgage.png">
</a>
<br/>
<p>Rent or Mortgage</p>
</div>
since the question asks for javascript, heres an option for updating the background-color of an element using the built-in js.style method
//get a handle on the link
//only one element w/ className 'expenseIcon'
//first child of 'expenseIcon' is the anchor tag
var link = document.getElementsByClassName('expenseIcon')[0].children[0];
//get a handle on the image
var image = link.children[0];
//listen for click on link & call bgUpdate()
link.addEventListener('click', bgUpdate, false);
function bgUpdate() {
if(image.style.backgroundColor === 'lightgoldenrodyellow'){
image.style.backgroundColor = 'aliceblue';
} else if (image.style.backgroundColor === 'aliceblue') {
image.style.backgroundColor = 'lightgoldenrodyellow';
}
else console.log('image bgColor: ' + image.style.backgroundColor);
}
a similar example
css
.expenseIcon{
background: red;
}
.colorToggle {
background: blue;
}
jquery
$(".expenseIcon").click(function () {
$('.expenseIcon').toggleClass('colorToggle');
});
By default, the div will have expenseIcon background. ToggleClass will toggle the div class with colorToggle so will override the previous color.
You don't need an hyperlink tag A to manage clicks, just put it on the DIV.

Change colour of td in dynamic table generated in php

I'm creating a PHP script that will dynamically generate tr and td elements for a table. When the user clicks in a specific cell in the first column, an AJAX function executes to display additional content. This is working as it should, however, I'm having trouble with what should be simple styling. When the user clicks on a given cell, I want that row to change colour (works) until they click on another cell (doesn't work).
Since my PHP file is rather large, I'm only posting the relevant parts.
<?php
$myFiles = showMyAttrs();
foreach($myFiles as $myFile) {
echo("<tr class = 'gradeC' onClick = 'changeColour(this)' onchange = 'restoreColour(this)' >");
echo("<td onClick = 'sendCell(this)' ><img src = $msEx /></td>");
echo("<td>$myFile</td>");
echo("</tr>");
}
I've also tried using onblur instead of onchange but that gave the same result.
The Javascript functions:
function changeColour(z) {
z.style.backgroundColor = "#FFFFFF";
}
function restoreColour(y) {
y.style.backgroundColor = "#00FF00";
}
Before I also tried:
function changeColour(z) {
document.getElementsByTagName("tr").style.backgroundColor = "#00FF00";
z.style.backgroundColor = "#FFFFFF";
<!-- document.getElementsByTagName("td").style.backgroundColor = "#00FF00"; -->
}
function changeColour(z) {
z.style.backgroundColor = "#FFFFFF";
document.getElementsByTagName("tr").style.backgroundColor = "#00FF00";
}
$('tr').click(function() {
$('tr').css('backgroundColor', '#0F0');
$(this).css('backgroundColor', '#FFF');
});
With each of them (except the last), the colour does change to white, however, when the user clicks on any other row, the previous row doesn't return to green. I don't mind if this works with Javascript or JQuery, as long as it is compatible across browsers. Even a fancy CSS trick I'm fine with using.
You're on the right track. I think adding/removing a class would be a good way to go. You could try this:
jQuery
$('tr').on('click', function() {
$('tr').children('td').removeClass('active');
$(this).children('td').addClass('active');
});
CSS
.active { background-color: yellow; }
See jsFiddle
Try using a css class to assign the background color:
$('.gradeC td').on('click',function(e){
if(!$(this).closest('tr').hasClass('green')){
$(this).closest('tr').addClass('green');
}else{
$(this).closest('tr').removeClass('green');
}
});
See demo here

how to make javascript function call two divs

i am trying to make a colour change when a button is clicked and i managed to do this however i want to change the colour of not just the main content container but more containers how do i do this?
function changeblackandwhite(objDivID) {
if(document.getElementById(objDivID).style.color=='black'){
document.getElementById(objDivID).style.color='white';
document.getElementById(objDivID).style.backgroundColor='black';
}
else if(document.getElementById(objDivID).style.color=='white'){
document.getElementById(objDivID).style.color='black';
document.getElementById(objDivID).style.backgroundColor = 'white';
}
else{
document.getElementById(objDivID).style.color='black';
document.getElementById(objDivID).style.backgroundColor='white';
}
}
<img src="images/colour.jpg" title="Change Text/Backgroud Colors">
There are dozens of ways you can accomplish this.
You could change the argument of your function to be an array of strings. You could also reduce the complexity of your function as well
<script type="text/javascript">
changeblackandwhite = function() {
for( var idx=0; idx < arguments.length; idx++) {
var tgtDiv= document.getElementById(arguments[i]);
if(tgtDiv.style.color=='black'){
tgtDiv.style.color='white';
tgtDiv.style.backgroundColor='black';
}
else{
tgtDiv.style.color='black';
tgtDiv.style.backgroundColor='white';
}
}
};
</script>
<img src="images/colour.jpg" title="Change Text/Backgroud Colors">
As another reader questioned - you can do this with jQuery in a single line.
With jQuery, you can declare the elements in question to have a class attribute.
Using jQuery, you can then do something like:
$('div.someClass').css({'color': 'black', 'background-color': 'white'});
The argument to jQuery can be a class based selector, an id based selector, or any other selector you choose.
If you are open to jquery and you assign 1 class in common with these two divs you can do the following:
This should get you started (see this jsfiddle): I changed the fiddle to include a neater solution where clicking on the button adds and removes classes on the containers which allows you to set multiple attributes including the text color in one quick call.
<div class='container'>
</div>
<div class='container'>
</div>
<button id="changeColor" type="button">Change Color </button>
<script type="text/javascript">
$(document).ready( function() {
$('#changeColor').click( function() {
if ($('.container').hasClass("blackContainer")){
$('.container').addClass("whiteContainer");
$('.container').removeClass("blackContainer");
} else {
$('.container').removeClass("whiteContainer");
$('.container').addClass("blackContainer");
}
});
});
</script>
//CSS
.blackContainer {
background-color: black;
color: white;
}
.whiteContainer {
background-color: white;
color: black;
}
I made a jsfiddle for you to play around with jsfiddle
I also did the javascript/jQuery in a similar way as the OP since it usually helps them understand.
As stated above, there are several different ways to do this, I've done but one.
The document.ready function sets up an event listener for the object to be clicked, most of the time this is how you'll see events coded. So when the link is clicked, it calls the function with the string name of the object the listener is for.
$(document).ready(function() {
$("#changeit").click(function(){
changeblackandwhite("Maincontainer");
})
});
After the event listener is assigned, it will call the function below when the link is clicked on.
// Here's your function, put the current color in a var, check if it's black
// if black, change colors, else make it black.
function changeblackandwhite(objDivID) {
var curColor = $("#" + objDivID).css("color");
if( curColor == 'rgb(0, 0, 0)'){
$("#"+objDivID).css({'color':'white','background-color':'black'});
} else {
$("#"+objDivID).css({'color':'black','background-color':'ghostwhite'});
}
}

How to write hoverHandler in JavaScript to change color of an element when hovering?

function hoverHandler(e)
{
if(event.target.getAttribute("id") != "hovering")
{
event.target.setAttribute("id", "hovering");
}
}
This is the code I have, I also have a CSS that sets the color when id is hovering.
The problem:
1) As I am hovering, the color does not get reset back to previous color when I leave the element
Can't you just use Css to solve the problem?
Something like
.element:hover
{
background-color: #FF0000;
}
where element is the class name
try adding, and make sure your checking for onmouseout as well
<script>
function hoverHandler(e)
{
if(e.id=="red") // hovering
{
e.id="blue";
}else {
e.id="red";
}
}
</script>
<span onmouseover="hoverHandler(this)" onmouseout="hoverHandler(this)">test</span>
or an inline event handlers could be
<style>#startStyle {color:lime} #red {color:red}#blue{color:blue}</style>
<span onmouseover="this.id='red'" onmouseout="this.id=''">test</span>
onmouseout would default back to the base style if any; or
<span onmouseover="this.id='red'" onmouseout="this.id='startStyle'">test</span>

Categories

Resources