I want to dynamically resize an element upon clicking and have the ability to revert back to its original size upon a second click. I thought toggleClass could do the job, but apparently it didn’t:
$(document).ready(function() {
$(this).click(function() {
var new_size = // dynamically calculated value;
$('.resize').css({'width': new_size, 'height': new_size});
$(this).toggleClass('resize');
});
});
Is there an easy way to work around this?
This line of code:
isn’t doing what you think it is. For your object to change size when you add a class, you need an actual CSS rule that specified the
.resizeclass which won’t work with a dynamically calculated size.This line of code is just setting a height and width on any object with the
.resizeclass and isn’t doing anything to objects without that class. Thus, you could resize the object once (when it had the class) and never change it’s size again. It won’t toggle anything.What I would suggest is that you save the old size and then you can restore it when you want to and also save the toggle value. jQuery’s .data() functions work well for saving this type of info: