0

I want a div to expand to the right on click from its current width (400px) to a certain specified width. (The divs have photos as backgrounds so the end result width will be different in each case, but it will be about 1000px in most cases).

How can I do this with jquery/javascipt? Thanks

user852974
  • 2,242
  • 10
  • 41
  • 65

2 Answers2

2

With a defined width:

$(".clickElement").click(function(){
    if($(this).is(".open"))
    {
        $(this).animate({ width: 400}, 500);
    }
    else
    {
        $(this).animate({ width: 1000}, 500);
    }
    $(this).toggleClass("open");
});

Checking the width of the image (background):
See this fiddle: http://jsfiddle.net/4ZfsD/2/

function toggle() {
    if ($(this).is(".open")) {
        $(this).animate({
            width: 400
        }, 500);
    }
    else {
        $(this).animate({
            width: $(this).data("width")
        }, 500);
    }
    $(this).toggleClass("open");
}
$("#test").click(function() {
    // No image width yet, we have to get it from the image
    if (!$(this).data("width")) {
        var img = new Image();
        var _this = $(this);

        img.onload = function() {
            // Image is loaded, save the width and call the toggle function
            _this.data("width", this.width);
            toggle.call(_this);
        }
        img.src = $(this).css("backgroundImage").replace("url(\"", "").replace("\")", "");
    } else { // We already got a width, just call toggle function
        toggle.call(this);
    }
});

CSS:

#test
{
     width: 400px;
 height: 400px;
 background-image:url("http://lokeshdhakar.com/projects/lightbox2/images/image-2.jpg");   
}
Niels
  • 48,601
  • 4
  • 62
  • 81
0

Using Jquery

<div id="box">Click me to grow</div>

  <script>
  $("#box").one( "click", function () {
  $( this ).css( "width","+=200" );
  });
  </script>
Edouard Tabet
  • 158
  • 1
  • 10