2

I'm trying to toggle the width of a div with a button.

Desired effect would be clicking 'Big' makes the div width 100% and the button reads 'Small' to reduce the div back to 50%.

Live example - JS Fiddle

HTML

<div class="block">
    block 50%
</div>
<button>Big</button>

CSS

.block {
    background: green;
    width: 50%;
    height: 300px;
    float: left;
    display: block;
    color: white;
}
button {
    clear: both;
    float: left;
    margin-top: 30px;
}
3
  • What are you having trouble with? Commented Aug 18, 2013 at 20:38
  • 1
    I don't see any jQuery code so I suggest you take a look at this learn.jquery.com/using-jquery-core/css-styling-dimensions Commented Aug 18, 2013 at 20:39
  • Im trying to toggle styles of the green div by clicking the 'Big' button Commented Aug 18, 2013 at 20:39

3 Answers 3

4

Try this

$(document).ready(
$('#resize').click(function(){
    var value = $(this).html();
    if(value=='Big'){
        $(this).html('Small'); 
        $('div').css('width',"100%");
    }else{
    $(this).html('Big');
    $('div').css('width',"50%");
    }

})
)

http://jsfiddle.net/tvXyL/6/

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

1 Comment

You're passing an incorrect argument to $(document).ready. You should wrap what you're passing right now in a function.
0

You'll need to use JavaScript for this job. From what I see you're using jQuery (as you tagged it), so this might work for you:

// Give the button a default state
$('button').attr('data-state', 'expand');

$('button').click(function () {
    // When clicked

    if ($(this).attr('data-state') === 'expand') {

        // If it's in "expand" status, expand the div
        $('.block').css('width', '100%');
        $(this).text('Small').attr('data-state', 'compress');
    } else if ($(this).attr('data-state') === 'compress') {

        // If it's in "compress" state, compress the div
        $('.block').css('width', '50%');
        $(this).text('Big').attr('data-state', 'expand');
    }
});

JSFiddle.

Comments

0

Add this jQuery to simply toggle classes.

jQuery

$('button').on('click', function(event) {
    if($('.block').hasClass('expand') == false) {
        $('.block').addClass('expand');
        $(this).text('Small');
    } else {
        $('.block').removeClass('expand');
        $(this).text('Big');
    }
});

Add an .expand class to your CSS.

CSS

.block.expand {
    width: 100%;
}

JSfiddle here: http://jsfiddle.net/RyN7d/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.