0

I have a heading in my html which is colored red using css. I want to test whether the css is applied to that heading and alert a message if it is applied using jQuery.

Her is my code.

<html>
<head>  
    <script src="http://code.jquery.com/jquery-1.4.3.min.js" ></script>
    <script>    
        $(document).ready(function() {
            $('#validate_btn').click(function() {
                $('.style').each(function() {
                    if($(this).css('color') == 'red') {
                        alert("css applied");
                    }
                }); 
            }); 
        });
    </script>
    <style>
    .style {
        color: red;
    } 
    </style>
</head>
<body>
    <h1 class="style">Heading One</h1><br><br>
    <div class="myClass">
        <span class="cos_validate_button" id="mybtn">
            <button  id="validate_btn">Check</button>
        </span>
    </div>
</body>
</html>
2
  • 2
    $('style') should be $('.style'). Also, when you debug, you may see that the color isn't represented the way you think it is. Commented Aug 1, 2014 at 16:06
  • $(this).css('color') <-- not going to return "red" Commented Aug 1, 2014 at 16:09

4 Answers 4

1

Get the style whitch will return in this form rgb(x,x,x) then convert it to hex and check

DEMO: http://jsfiddle.net/bP7sP/

$(document).ready(function () {
    $('#validate_btn').click(function () {
        if(rgbToHex($('.style').css('color')) == "#ff0000"){
            alert("RED");
        }
    });

    var hexDigits = new Array
        ("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"); 
    function rgbToHex(rgb) {
        rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
        return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
    }
    function hex(x) {
        return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
    }
});
Sign up to request clarification or add additional context in comments.

5 Comments

Why is this rated down? please explain, it does exactly what the op wanted.
Why do you convert the color to hex value? It's a waste of time, you can just check the RGB value like $('.style').css('color')) == "rgb(255, 0, 0)"
Because when you compare two strings its better not to have spaces in there and extra charectors, there will be a big chance or error. E.g rgb(255,0, 0) != rgb(255, 0, 0)
Yes but you should know that jQuery always returns colors in the RGB string format with spaces after commas (plus in the common language, not adding a space after a comma is a grammatical error). If you want to be sure then you can do .replace(/ /g, '') to remove all spaces, which is pretty easier than your solution.
You are right, but I just took a different approach, doesn't make my answer bad. anyways thanks.
0

Why all this complicated code?

Make it easier:

<html>
<head>  
    <script src="http://code.jquery.com/jquery-1.4.3.min.js" ></script>
    <style>
        .style { color: red }
    </style>
</head>
<body>
    <h1 class="style">Heading One</h1><br><br>
    <div class="myClass">
        <span class="cos_validate_button" id="mybtn">
            <button  id="validate_btn">Check</button>
        </span>
    </div>
    <script>
        $('#validate_btn').click( function() {
            $('.style').eq(0).css('color') == "rgb(255, 0, 0)" && alert('Style applied!');
        });
    </script>
</body>
</html>

4 Comments

NOTE: FYI you don't even need jQuery to do this.
@Marco.I want it to alert when the check button is clicked using jquery only. In your case its alerting when the page loads.
@user3885720 Sorry, I edited the code, now it will work clicking the button!
I think comparing to strings with spaces leave a good chance of messing up, thats why I convert to hex color first then compare against something like "#ff0000" instead. See my answer.
0

When .css returns a color it returns it as an RGB value, not the name of the color.

To make sure you're matching the right pattern do this first to get the RGB value:

 $('style').each(function(){
    alert($(this).css('color'));
 });

then use that value in your if statement.

2 Comments

@Matt.I dont want to alert color. I want to alert a message.and can you do this in jsfiddle?
I know, thats not what I meant. If you alert the color first you can capture the string you need to check against your if statement. its called debugging code. You remove it afterwards
0

I would recommend something like this: http://jsfiddle.net/9S6fS/

<h1 class="redHeader someHeader">Heading One</h1><br><br>
<h1 class="someHeader">Heading Two</h1><br><br>

...

$('.someHeader').each(function() {
    if($(this).hasClass('redHeader')) {
        alert("css applied to " + $(this).text());
    }
}); 

It is good practice to use class names that explain what the class is used for. It will make your code more readable. By giving all your headers a class (someHeader) and your red headers a class too (redHeader) you significantly simplify your problem and allow your code to be extended more easily.

For instance, if your redHeader class is actually an activeHeader, say in some navigation control, you may want to be applying different styles in the future (ex:blue and bold text). Using classes this way would not break your javascript when you make the change.

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.