jQuery cannot assign to a function result - javascript

I am getting the error in the title above in the following code:
$j(".table").delegate('td','click', function(e) {
//alert($j(this).parent().css('background-color'));
if ($j(this).parent().css('background-color') == 'transparent')
$j(this).parent().css('background-color') = '#eee';
else {
$j(this).parent().css('background-color') = 'transparent';
}
});
I don't understand why I'd be getting this error, as I have made sure I am using the assignment operator == to compare the strings

There are 2 issues with your question: first one is already answered by #Mike Vranckx, the correct usage of .css() setter is passing a second argument to set as value.
The other problem is that your condition will never be true, I'll address it in this answer. If you fix it in the way I suggest, you won't be needing .css().
Computed CSS values, which are returned from getComputedStyle/jQuery's .css(), are not exactly what you've authored in your code -- they suffer transformations when parsed into the CSSOM.
For instance, in Chrome:
body { background-color: transparent; }
console.log( $('body').css('background-color') ); //returns "rgba(0, 0, 0, 0)"
See for yourself.
That's why your $(...).('background-color') == 'transparent' condition is always false.
The most clean and cross-browser solution is to apply styling with classes (.addClass(), removeClass(), toggleClass()) and do conditional checks with .hasClass().
In your case though, .toggleClass should suffice. Here's a simple way to write your logic (fiddle):
$j(".table").on('click', 'td', function() {
$j(this).parent().toggleClass('bg-gray');
});
.bg-gray {
background: #eee;
}

To set / change the background-color property, you need to pass it as a second argument:
$j(this).parent().css('background-color', '#eee');

While compare using background color better to use rgba like this
$j(this).parent().css('background-color', 'rgb(0,0,0)');

To assign value to css, pass the value as a second argument.
The below line will change to
$j(this).parent().css('background-color') = '#eee';
The following Line
$j(this).parent().css('background-color','#eee');

It would be cleaner, faster, and easier to modify to use a CSS class :
.table td { background-color: transparent; }
.foo { background-color: #EEE; }
And
$j( '.table' ).delegate( 'td', 'click', function() {
$( this ).toggleClass( 'foo' );
});
Also avoid using reserved words like "table" for class names, it's confusing.

Related

How to dynamically change a class css styling?

Goal
In my program I want to do both things with jquery/javascript:
Change styling of css classes dynamically
Add/remove classes to elements
Problem
To do the first thing I use $(".className").css() method, but it changes style only for those elements that already have className class, i.e. if I later add className to an element its style won't be new. How can I solve this?
Example
See it also at jsfiddle.
$("p").addClass("redclass");
$(".redclass").css("color", "darkRed");
$("span").addClass("redclass");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>I want to be red! And I am.</p>
<span>I want to be red too but I'm not :'(</span>
Result:
A more shorten format:
$("<style/>", {text: ".redclass {color: darkRed;}"}).appendTo('head');
The snippet:
$("<style/>", {text: ".redclass {color: darkRed;}"}).appendTo('head');
$("p").addClass("redclass");
$("span").addClass("redclass");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>I want to be red! And I am.</p>
<span>I want to be red too but I'm not :'(</span>
While other (working) answers have been supplied, they don't actually answer your question - namely, they don't change the specified css class, but instead override it by adding another rule later in the document.
They achieve this, basically:
Before
.someClass
{
color: red;
}
After
.someClass
{
color: red;
}
.someClass
{
color: white;
}
When in many cases, a better option would see the color attribute of the existing rule altered.
Well, as it turns out - the browser maintains a collection of style-sheets, style-sheet rules and attributes of said rules. We may prefer instead, to find the existing rule and alter it. (We would certainly prefer a method that performed error checking over the one I present!)
The first console msg comes from the 1 instance of a #coords rule.
The next three come from the 3 instances of the .that rule
function byId(id){return document.getElementById(id)}
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded(evt)
{
byId('goBtn').addEventListener('click', onGoBtnClicked, false);
}
function onGoBtnClicked(evt)
{
alterExistingCSSRuleAttrib('#coords', 'background-color', 'blue');
alterExistingCSSRuleAttrib('.that', 'color', 'red');
}
// useful for HtmlCollection, NodeList, String types (array-like types)
function forEach(array, callback, scope){for (var i=0,n=array.length; i<n; i++)callback.call(scope, array[i], i, array);} // passes back stuff we need
function alterExistingCSSRuleAttrib(selectorText, tgtAttribName, newValue)
{
var styleSheets = document.styleSheets;
forEach(styleSheets, styleSheetFunc);
function styleSheetFunc(CSSStyleSheet)
{
forEach(CSSStyleSheet.cssRules, cssRuleFunc);
}
function cssRuleFunc(rule)
{
if (selectorText.indexOf(rule.selectorText) != -1)
forEach(rule.style, cssRuleAttributeFunc);
function cssRuleAttributeFunc(attribName)
{
if (attribName == tgtAttribName)
{
rule.style[attribName] = newValue;
console.log('attribute replaced');
}
}
}
}
#coords
{
font-size: 0.75em;
width: 10em;
background-color: red;
}
.that
{
color: blue;
}
<style>.that{color: green;font-size: 3em;font-weight: bold;}</style>
<button id='goBtn'>Change css rules</button>
<div id='coords' class='that'>Test div</div>
<style>.that{color: blue;font-size: 2em;font-weight: bold;}</style>
#synthet1c has described the problem. My solution is:
$("head").append('<style></style>');
var element = $("head").children(':last');
element.html('.redclass{color: darkred;}');
What you are having issue with is that when you use the jQuery selector $('.redclass').css('color', 'darkRed') you are getting all the elements that currently have that class and using javascript to loop over the collection and set the style property.
You then set the class on the span after. Which was not included in the collection at the time of setting the color
You should set the class in your css file so it is distributed to all elements that have that class
console.log($('.redclass').length)
$("p").addClass("redclass");
console.log($('.redclass').length)
// $(".redclass").css("color", "darkRed");
$("span").addClass("redclass");
console.log($('.redclass').length)
.redclass {
color: darkRed;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>I want to be red! And I am.</p>
<span>I want to be red too but I'm not :'(</span>

Jquery adding and removing elements dynamically

I am trying to add and remove a span element dynamically. it's throwing syntax errors like
expected ')' and expected ';'
please help me to fix it.
<script type="text/javascript">
$(document).ready(function () {
$("input[data-required='true']").focus(function () {
$(this).css({ 'background-color': 'red' }).after("<span class="label_error;"style="color:red;font-size:10pt">This field is required</span>");
});
$("input[data-required='true']").blur(function () {
$(this).css({ 'background-color': 'white' }).remove("<span class="label_error;"style="color:red;font-size:10pt">This field is required</span>") ;
});
});
</script>
The way that you are concatenating the values in your HTML string is wrong,
.after("<span class='label_error' style='color:red;font-size:10pt;'>" +
"This field is required" +
"</span>");
To fix this issue either you can use single quote in your string wrapped by double quotes or try to escape the double quote by using \ like "avi\"s code is wrong".
On top of all, the best approach would be creating element by using jquery,
.after($("<span>", {class : 'label_error',
style : 'color:red;font-size:10pt;',
text : 'This field is required'
}));
This would be more readable and maintainable. And I forgot to spot another one error that you made in your code. You are using .remove() in a wrong way,
$("input[data-required='true']").blur(function () {
$(this).css({ 'background-color': 'white' }).next("span.label_error").remove();
});
You have to select the relevant element from your $(this) object and invoke remove over it.
And the best approach for finishing up your task is, allot the styling works to be done to the css by writing rules with relevant selectors (said by #rory)
input[data-required='true'] {
background-color: white;
}
input[data-required='true']:focus {
background-color: red;
}
span.label_error {
color: red;
font-size: 10pt;
}
And the js would be,
var errorMsg = $("<span>", {class: 'label_error',text: 'This field is required'});
$("input[data-required='true']").focus(function() {
$(this).after(errorMsg);
}).blur(function() {
$(this).next("span.label_error").remove();
});
DEMO
You have two issues. Firstly you need to use different quotes to delimit the string to those you use within the string. Helpfully, in JS you can use either single (') or double (") quotes to achieve the same purpose. Also, the class attribute should not have a trailing ;. It can be helpful to use a text editor which has syntax highlighting as it makes it nearly impossible to miss mistakes like that.
Your second problem is that the remove() method expects a selector, not a whole HTML string. To remove the span which was appended in the focus event, use next() to select it, then remove(). Try this:
$("input[data-required='true']").focus(function () {
$(this).css({ 'background-color': 'red' }).after('<span class="label_error" style="color: red; font-size: 10pt">This field is required</span>');
});
$("input[data-required='true']").blur(function () {
$(this).css({ 'background-color': 'white' }).next('span').remove();
});
Finally, note that it is much better practice to define your styles in CSS as it separates the HTML/JS from the styling rules, and helps make the JS shorter as well. Try this:
input[data-required='true'] {
background-color: white; /* transparent may work here too */
}
input[data-required='true']:focus {
background-color: red;
}
span.label_error {
color: red;
font-size: 10pt;
}
$("input[data-required='true']").focus(function () {
$(this).after('<span class="label_error">This field is required</span>');
}).blur(function () {
$(this).next('span').remove();
});
Working example

efficient way to look for all css uses of a color

What is the most efficient way to look for all uses of a css color in the "current page" ?
For me a use of a color appear as color-background, font color, border color.
In table TDs, Divs, Span, paragraph (P), etc....
I think to do a similar "loop" to this one is overkill for a full page, and this one is just searching a specific HTML tag (DIV) and verifying only the "color", not the other properties....
$("div").each(function () {
var color = $(this).css("color");
if (color == "#F1F2F3") {
console.log('found it!');
}
});
Isn't there a easiest way to simple say: "replace all HEX color #XXXXXX value for #YYYYYY ?????
In css I might even represent the color in different ways (at least 5 ways):
background-color: #000000;
color: #000;
border: 1px solid rgb(0,0,0);
border-bottom-color: rgb(0%,0%,0%);
outline-color: black;
Update 1
I took Garath sugestion and I worked a little on it (all selector with exclusion, etc), but I am still not so happy about it..... I am still trying to identify all different properties where the color might exist, and I am not even paying attention to the way the browser will return me the color.....
$('*:not(head, script,link, meta, title)').filter(function() {
var replace = 'rgb(0, 0, 0)';
var replaceFor = '#FF0000';
if( $(this).css('color') == replace) $(this).css('color', replaceFor);
if( $(this).css('background-color') == replace) $(this).css('background-color', replaceFor);
if( $(this).css('border-color') == replace) $(this).css('border-color', replaceFor);
});
It would be so great to have a similar way to this one Attribute Equals Selector [name="value"], but where I would not need to specify the attribute type...
Instead of each function you can use filter, but still it have to check all elements - fortunately it the complexity of this check is linear.
The snippet could look like this:
$('div').filter(function() {
var match = '#F1F2F3';
return ( $(this).css('color') == match );
}).css('color', '#YYYYYY');

jquery/javascript - how to "undo" a click event using if statement?

The below code takes into account different tags and turns the background red if the tag is clicked on. I want to code it so that if it is clicked on again, it changes back from red and 'deletes' the background, or at least set it to null. I have tried an if statement to no avail. I know that I can just make another click event that changes the background to white, but this is for experimental purposes and i was wondering if this CAN be done with if statements. thanks to ya.
<script>
$(document).ready(function() {
$("p, h1").click(function() {
$(this).css("background-color", "red");
if ($(this).css("background-color", "red")) {
$(this).css("background-color", "null");
}
});
});
</script>
First you need to use the getter version of .css() like
if($(this).css("background-color") == "red"){
but it still won't work because, the css getter will return a rgb format value and will return non consistent values across browsers.
So the solution is to use a css based solution using toggleClass()
.red {
background-color: red;
}
then
$(document).ready(function() {
$("p, h1").click(function() {
$(this).toggleClass("red");
});
});
Demo: Fiddle
$('p, h1').click(function() {
var $this = $(this);
var altColor = $this.data('altColor');
$this.css('background-color', altColor ? '' : 'red');
$this.data('altColor', ! altColor);
});
This answers your question, but you should really be using a CSS class for this.
This is easily done using CSS, and is a bit more straight forward. If you create a CSS class for the click, then you can just toggle it on/off each time the item is clicked:
CSS
p, h1 {
background-color: none;
}
p.red, p.h1 {
background-color: red;
}
JavaScript:
$('p, h1').click(function() {
$(this).toggleClass('red');
});

jQuery check if .css property was set

My code looks like this
if($(element).css("background-color") == null){
$(element).css("background-color", "white");
}
I want to make sure that if the color wasn't set in the style.css file, I add it. But that code is not working. It's always returning rgba(0,0,0,0). The browser I am working with is Chrome.
Is there another way to check if the color wasn't set?
CSS:
.background-set { background-color: white; }
jQuery:
var $el = $(element);
if( !$el.hasClass('background-set') ){
$el.addClass('background-set');
}
Though I'm not sure why you'd need to check. You can just add it without the condition.
Alternatively:
if ( $el.prop('style').backgroundColor == '' ) {
...
}
or
if ( $el.get(0).style.backgroundColor == '' ) {
...
}
The method suggested by elclanrs is the most elegant way of handling this and should be the preferred method. However, for the sake of sating curiosity, you could achieve the same result using a jQuery Attribute Contains Selector.
$("div[style*='background-color']").text("I have a background color!");
jsFiddle demo

Categories

Resources