1

I am trying to add a class .red to #box-1 on scroll down using following code at this demo.

$(window).scroll(function() {    
    var scroll = jQuery(window).scrollTop();
    if (scroll >= 30) {
        $("#box-1").addClass("red");

    } else {
        $("#box-1").removeClass("red");

    }
});

the HTML:

<div id="box-1" class="row"></div>
<div id="box-2" class="row"></div>
<div id="box-3" class="row"></div>

and CSS:

.red{ background-color: red;  }
#box-1{background-color: yellow;   height:300px; width:100px;}
#box-2{background-color: green;   height:300px; width:100px;}
#box-3{background-color: blue;   height:300px; width:100px;}

But it is not working! What am I doing wrong?

2
  • add !important > .red{ background-color: red !important; } Commented Jan 11, 2015 at 11:59
  • 1
    use !important; is bad practice... Commented Jan 11, 2015 at 12:03

2 Answers 2

1

Adding !important to the background-color of the red class does the trick.

ids identify elements. classes classify elements. ids have higher specificity and so their styles have higher precedence.

.red{ background-color: red !important; }

See fiddle : http://jsfiddle.net/2v9fn1np/1/

Using !important is bad practice and usually an indicator that you have not utilized classes and ids effectively. In this case, to add the style, you can edit the style attribute of the element directly and achieve the highest precedence. Use jQuery's css method.

Sign up to request clarification or add additional context in comments.

Comments

0

If you haven't noticed, the is getting the CLASS "red". The problem is that you've referred to it's ID has having a yellow background. And since the ID is predominante over a CLASS, you must add it to the CLASS, EX:

#box-1.red{ background-color: red; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.