Reputation: 325
I am using j-query to set the height of a div same as width.It is now running on-load, but I want it to run on window resize.
I'm using this :
<script>
$(document).ready(function(){
$('.source').each(function(){
var currentWidth = $(this).width();
$(this).height(currentWidth);
})
})
Upvotes: 0
Views: 127
Reputation: 9637
use window.resize() event in jquery
function test() {
$('.source').each(function () {
var currentWidth = $(this).width();
$(this).height(currentWidth);
});
}
$(document).ready(function () {
test();
$(window).resize(test);
});
Upvotes: 0
Reputation: 41822
This is just modification code of @Bala
// ready event
$(function () {
function test() {
$('.source').each(function () {
var self = $(this);
self.height(self.width());
// but how the width is changing?
});
}(); //calling the function
// resize event
$(window).resize(test);
});
BTW, how the width is changing?
Upvotes: 0
Reputation: 11042
$(window).on('resize', function(){
$('.source').each(function(){
var currentWidth = $(this).width();
$(this).height(currentWidth);
});
});
$(document).ready(function(){
$('.source').each(function(){
var currentWidth = $(this).width();
$(this).height(currentWidth);
});
});
or even better, put the duplicate code into a separate function:
$(window).on('resize', function(){
changeWidth();
});
$(document).ready(function(){
changeWidth();
});
function changeWidth() {
$('.source').each(function(){
var currentWidth = $(this).width();
$(this).height(currentWidth);
});
}
Upvotes: 0
Reputation: 85545
You can use like this:
$(window).on('resize',function(){
$('.source').each(function(){
var currentWidth = $(this).width();
$(this).height(currentWidth);
})
}).resize();//runs at first load
Upvotes: 3