hmahdavi
hmahdavi

Reputation: 2354

change a attr of element when windows width less than value with jquery

I want when windows width less than 992, change css attr of one element. I wrote this code:

$(document).ready()
{
    if ($(window).width() < 992) {
        $('#header_right').css('text-align', 'center');
    }
}

If I execute

if ($(window).width() < 992) {
    $('#header_right').css('text-align', 'center');
}

in console by ff done but when use this code in file such as up don't worked.

I use this js file in head:

<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/main.js"></script>

Please advice.

Upvotes: 1

Views: 313

Answers (1)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

This is better solved by @media queries. You need to add this in your CSS:

@media screen and (max-width: 992) {
  #header_right {
    text-align: center;
  }
}

And you must bind this with the window's resize event, inside the document's ready function. Actually you have a syntax error there:

$(document).ready(function () {
  $(window).resize(function () {
    if ($(window).width() < 992) {
      $('#header_right').css('text-align', 'center');
    }
  });
});

Because the current code you have, checks only once when the document is loaded and not every time when the window is resized.

Upvotes: 2

Related Questions