0

I've got to be missing something really simple here. All I want to do is make the color of all list items with a class of "link" toggle between blue and black. I've read through half a dozen posts and haven't figured out an answer yet.

jfiddle: http://jsfiddle.net/Y8K2x/1/

HTML:

<button>Toggle Link Color</button>
<ul>
    <li class="item">Item 1</li>
    <li class="link">Link 2</li>
    <li class="item">Item 3</li>
    <li class="link">Link 4</li>
    <li class="link">Link 5</li>
    <li class="item">Item 6</li>
    <li class="link">Link 7</li>
    <li class="item">Item 8</li>
</ul>

Here's the JS:

$('button').click(function () {
var linkColor = $('.link').css('color');
if (linkColor == '#0099ff') {
    $('.link').css('color', '#000000');
} else if (linkColor == '#000000') {
    $('.link').css('color', '#0099ff');
}

});

3 Answers 3

1

Wouldn't it be easier (or cleaner) to just use:

jQuery

$('button').click(function () {
    $('.link').toggleClass('link, link1');
});

CSS

.link {
    color: #000000;
}
.link1 {
    color: #0099ff;
}

jsFiddle example

(BTW, jQuery returns RGB values for color, not hex)

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

1 Comment

+1, and from jquery website " Different browsers may return CSS color values that are logically but not textually equal, e.g., #FFF, #ffffff, and rgb(255,255,255)."
1

A simple console.log of linkColor will show that the color is in rgb format, not hex.

$('button').click(function () {

var linkColor = $('.link').css('color');

if (linkColor == 'rgb(0, 153, 255)') {

    $('.link').css('color', '#000000');

} else if (linkColor == 'rgb(0, 0, 0') {

    $('.link').css('color', '#0099ff');

}

});

Comments

0

Please try code maybe can help

$('button').click(function () {
    var that = $(this);

    if(that.hasClass('blue')) {        
         $('.link').css('color', '#000000');
         $('button').removeClass('blue');       
    } else {
        $('.link').css('color', '#0099ff');
       that.addClass('blue');

    }

});

Demo: http://jsfiddle.net/vsok/3qSkr/1/

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.