Omkar
Omkar

Reputation: 308

How to apply css dynamically by jquery with changed values?

I am trying to apply width to the 'div' as per user's screen resolution. For that I am using below jquery code:

$(function() {
  var resolution = $(window).width();
  var new_width = resolution - 17;
  new_width = new_width + "px";
  $("#box").css("width", new_width);
});

I am trying to change width dynamically but its not working.

If I give values statically by using $("#box").css("width", "500px"); it will take effect and sets the width to 500px but if I use new_width instead of 500px its not changing the width of div.
How do I fix it?

Upvotes: 0

Views: 41

Answers (4)

daniel
daniel

Reputation: 1433

By dynamically, do you mean on resize? Then you need the resize event:

$(window).resize(function() {
    var resolution = $(window).width();
    var new_width = resolution - 17;
    $("#box").css("width", new_width + "px");
});

Upvotes: 1

Kingrune
Kingrune

Reputation: 87

This is what I did when I has this problem:

var Width = window.screen.availWidth; //maximizes to screen's width

this is just javascript. may not be what you are looking for instead of using $(window).width();

Upvotes: 0

JVXR
JVXR

Reputation: 1312

You may want to make sure that the code to set the width is tied to an event. Right now it seems to set the width on page load i.e. window's width.

Upvotes: 0

Vaibhav
Vaibhav

Reputation: 447

By default div will take 100% width as it is block element. Make in inline block and try doing same thing.

Upvotes: 0

Related Questions