1

I have a CSS border property in place currently (border-left: 1px), and onClick, I have it removed via the first jQuery function below. How can I set this up so that my second function will add back the property upon the second click? It should switch back and forth per click.

$(function(){
    $('#button').click(function() {    
        $('#button-2').css('border-left','none');
    });   
    $('#button').click(function() {
        $('#button-2').css('border-left','1px');
    });
});

I have now included the original code: www.jsfiddle.net/tonynggg/frnYf/12

2 Answers 2

5

Would it be easier to define a css class:

.button { border-left: 1px; }
.buttonClicked { border-left: none; }

And then use the jQuery toggleClass

So your code would be:

$(function(){
    $('#button').click(function() {    
        $('#button-2').toggleClass('buttonClicked');
    });   
});

That would then toggle your alternate css class on an off when it's clicked. If nothing else, this should get you pointed in the right direction.

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

5 Comments

This is the best way, much better than hard-coding CSS into javascript files.
Interesting. Wasn't aware of the toggleClass method.
@M_M Unfortunately I couldn't get that to work. Here's the original code: jsfiddle.net/tonynggg/frnYf/12
there is no toggleCss method. Take a look at jsfiddle.net/frnYf/16 also, I would consider only creating one click event handler for #button.
@Tony my pleasure! Glad I could assist :)
1

First, create a class that has the border:

.borderclass
{
   border-left:1px black solid;
}

And then,

$(function(){
$('#button').click(function() {    
    if ($('#button-2').hasClass('borderclass'))
        $('#button-2').removeClass('borderclass');
    else
        $('#button-2').addClass('borderclass');
    });   

});

1 Comment

This code doesn't work unfortunately. Although it looks like the correct solution, I think maybe because the "hasClass" is not functional because #button-2 is not a class?

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.