2

Is it possible to override css dynamically?

Like in css we specify

.mainDiv{
   min-height:100px !important
 }

Is it possible to do the same with jquery css?

I've tried

$(".mainDiv").css({"min-height" : ($(window).height() * 0.7) +"px !important"});

But this doesn't work.

StuartLC
  • 104,537
  • 17
  • 209
  • 285
sam
  • 2,277
  • 4
  • 18
  • 25

9 Answers9

2

The best way is to overwrite the styles is using css, and not jquery. F.e. you can only add a class with jquery, and define the rest in your stylesheet.

//script to add a class, this can be anything
$('.mainDiv').click(function(){
    $(this).addClass('active');
});

//css to define the different min-heights. (I would not recommend using !important)
.mainDiv {
   min-height:100px !important;
}

.mainDiv.active {
   min-height:200px !important;
}
koningdavid
  • 7,903
  • 7
  • 35
  • 46
1

Try, important is not supported by JQuery

$(".mainDiv").css({"min-height" : ($(window).height() * 0.7) +"px"});

As This will be inline CSS, thus it will have preference

Satpal
  • 132,252
  • 13
  • 159
  • 168
1

It is definitely possible to override CSS dynamically. Is it the !important attribute that isn't getting applied?

It's true that it cannot be added with the .css() method. However, you can achieve this with the .attr() method:

$(".mainDiv").attr("style", "min-height: " + ($(window).height() * 0.7) +"px !important");

Source: How to apply !important using .css()?

Community
  • 1
  • 1
0

Try

$(".mainDiv").css({"min-height" : ($(window).height() * 0.7) +"px"});

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

Instead of quotes ("), use back ticks instead `, this is the only way jQuery updates css.

$(\`.mainDiv").css({"min-height" : ($(window).height() * 0.7) +"px !important\`});
StuartLC
  • 104,537
  • 17
  • 209
  • 285
Tryah85
  • 371
  • 3
  • 12
0

Try without the {}

$(".mainDiv").css("min-height", ($(window).height() * 0.7) +"px");

It's possible you may also need to do the calculation seperately, save it in a variable, and just use this variable, such as:

var newHeight = $(window).height() * 0.7;
$(".mainDiv").css("min-height", newHeight +"px");
Praxis Ashelin
  • 5,137
  • 2
  • 20
  • 46
0

Try this

$(".mainDiv").css({"min-height" : ($(window).height() * 0.7) +"px"});

or just

$(".mainDiv").attr('style',"min-height:"+($(window).height() * 0.7) +"px !important;");
sangram parmar
  • 8,462
  • 2
  • 23
  • 47
0

Check this fiddle. You can try $(".mainDiv").css({"min-height" : ($(window).height() * 0.7) +"px"});

Deepak Biswal
  • 4,280
  • 2
  • 20
  • 37
0

YOu can try this

$(document).ready(function() {
    $(".mainDiv").attr('style', 'min-height: ' +($(window).height() * 0.7) +"px !important");
});

FIDDLE DEMO

Refer For more Refer Here

Community
  • 1
  • 1
RONE
  • 5,415
  • 9
  • 42
  • 71