Hubrid
Hubrid

Reputation: 11

Changing css w/ javascript

So I have a link, that when clicked, i want its css values to change. I can do that with this jquery code:

    $(".linkname").click(function(){
  $(this).css({'border-style' : 'solid', 'border-width' : '1px', 'border-color' : '#ec6163', 'color' : '#ec6163'});
  return false;
});

However, I also want the link's css values to revert to normal when I click the link with the altered css values a second time. I tried an if else sentence, but it always evaluated else and didn't work. How can i do this?

Upvotes: 1

Views: 191

Answers (3)

Dawson
Dawson

Reputation: 7597

Have you tried using toggle()?

$('.linkname').toggle( function() {
        $(this).css({'border-style' : 'solid', 'border-width' : '1px', 'border-color' : '#ec6163', 'color' : '#ec6163'});
    }, function() {
        $(this).css({'border-style' : 'dotted', 'border-width' : '0px', 'border-color' : '#999999', 'color' : '#cc6163'});
});

Upvotes: 3

Bryan Downing
Bryan Downing

Reputation: 15472

Even better, put all of that CSS into a class and use toggleClass to switch.

/* CSS */
.someclass { border: 1px solid #ec6163; color: #ec6163; }

/* JS */
$(".linkname").click(function(){
    $(this).toggleClass('someclass');
    return false;
});

Upvotes: 5

threenplusone
threenplusone

Reputation: 2122

I am not sure why your if/else statement didn't work.
Perhaps try using a variable outside of the method to save which state the link is in.

eg.

var link_state = 1;

$(".linkname").click(function(){
  if (link_state == 1) {
    $(this).css({'border-style' : 'solid', 'border-width' : '1px', 'border-color' : '#ec6163', 'color' : '#ec6163'});
    link_state = 0;
  }
  else {
    $(this).css({'border-style' : 'none', 'border-width' : '0px', 'border-color' : '#ffffff', 'color' : '#ffffff'});
    link_state = 1;
  }
  return false;
});

Upvotes: 1

Related Questions