hussain nayani
hussain nayani

Reputation: 325

Run Jquery on window resize

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

Answers (5)

Balachandran
Balachandran

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

Mr_Green
Mr_Green

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

martincarlin87
martincarlin87

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

Bhojendra Rauniyar
Bhojendra Rauniyar

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

Refilon
Refilon

Reputation: 3489

$(document).resize(function(){
    //do things here
});

Upvotes: 0

Related Questions