Reputation: 418
I need help!
Let's say that I have an element in my page that changes background-color when scrolled. I wanted to change the color of the a tag inside of it whei it changes the background, I tried to write a thing like this below, but it did't work! How can I tell jquery to act when the background changes?
$(function () {
var background = $("backtotop").css('background', 'black');
if (background = true) {
$('a').css('color', 'white')
}
if (background = false) {
$('a').css('color', 'green')
}
});
Upvotes: 0
Views: 838
Reputation: 7878
Your code has several syntax issues:
$("backtotop")
is no valid selector, this would select the html-tag backtotop
and I don't know such a tag. Rather use a ID-selector (#
) or a class-selector (.
).
background
would be a jQuery-Object here and no boolean value.
if (background = true) {
, here you are setting the value true
to background
. So this statement is always true, you have to use the comparison-operater ==
instead.
$(function () {
var background = $("#backtotop").css('background-color', 'black');
var backgroundcolor = background.css('background-color');
if (backgroundcolor == 'rgb(0, 0, 0)') {
$('a').css('color', 'white')
} else {
$('a').css('color', 'green')
}
});
Note: The getter .css()
-function will return the rgb-value of the set background color.
A second approach for using classes:
$(function () {
var background = $("#backtotop").addClass('black')
if (background.hasClass('black')) {
$('a').css('color', 'white')
} else {
$('a').css('color', 'green')
}
});
Reference
Upvotes: 2
Reputation: 418
Thanks a lot for your answers guys. I think the easiest way is to use .addClass and .removeClass, because none of the suggested methods trying to fix my piece of code worked out.
It's a shame, however, because I think that the idea of make it act as the background changes is very cool. I think the problem is that the variable doesn't interact with the if statements.
When on the code
$(function () {
var background = $("backtotop").css('background', 'black');
if (background = true) {
$('a').css('color', 'white')
}
if (background = false) {
$('a').css('color', 'green')
}
});
I use single = the color of the a tag stays permanently white, If I use double == the color stays green.
Upvotes: 0
Reputation: 29683
if you are getting string from the below line
var background=$("backtotop").css('background','black');
then do this
if (background == "true") {
$('a').css('color', 'white')
}
if (background == "false") {
$('a').css('color', 'green')
}
if you are getting boolean value then write as below
if (background) {
$('a').css('color', 'white')
} else {
$('a').css('color', 'green')
}
Upvotes: 1
Reputation: 1331
$(function(){var background=$("backtotop").css('background','black')
if(background == true){$('a').css('color','white')}
if(background == false){$('a').css('color','green')}});
Upvotes: 1