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
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");
}
Using Jquery
<div id="box">Click me to grow</div>
<script>
$("#box").one( "click", function () {
$( this ).css( "width","+=200" );
});
</script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.