1

I would like to add dynamically using Jquery a rule to an existing class but that is not attributed to an HTML element until the user clicks a button.

I tried :

$('.show-toggle').css("max-height", width * 0.5);

as suggested in How to add property to existing class but I think it does not work because the class is not active at first.

HTML

<div id ="toggler"></div>
<div id = "toogle" class="hide-toggle">

CSS

.hide-toggle {
display:none
}

.show-toggle {
display : block;
}

JS (with Jquery)

$('#toggler').click(function () {

var width = $(window).width();
$('.show-toggle').css("max-height", width * 0.5);
$("#toggle").toggleClass('hide-toggle').toggleClass('show-toggle');

});
Community
  • 1
  • 1
Geniom
  • 13
  • 5
  • You don't have an html element with the class `show-toggle`. – Offir Nov 17 '16 at 12:55
  • 1
    you are forget to add `.` in `Show-toggle` class and both class are different `Show-toggle` and `show-toggle` – Minal Chauhan Nov 17 '16 at 12:55
  • Thanks. Edited, this was a typo in SO and not in my code. – Geniom Nov 17 '16 at 12:58
  • @OffirPe'er yes, so you confirm that it's not possible to change a class in the css file because it's not attributed (yet)in the html ? – Geniom Nov 17 '16 at 13:07
  • 1
    I don't think it's possible to change CSS class using javascript. `$('.show-toggle').css("max-height", width * 0.5);` refers to an html element with the class `show-toggle`, but not to the class in the style sheet. – Offir Nov 17 '16 at 13:09
  • This link could be of helpful to you http://stackoverflow.com/questions/16965515/how-to-get-a-style-attribute-from-a-css-class-by-javascript-jquery – Geeky Nov 19 '16 at 04:58

1 Answers1

0

Put the .css() after the .toggleClass():

$(document).ready(function(){
    $("#toggler").click(function(){
    var width = $(window).width();
    $("#toggle").toggleClass("hide-toggle, show-toggle");
    $(".show-toggle").css("max-height", width*0.5);
  });
});

So that the change of CSS can be executed after the #toggle has class of .show-toggle. Because jQuery cannot execute the .css() on a class .show-toggle when there is no element with class .show-toggle

Fiddle: https://jsfiddle.net/p15rcmn4/4/

Aircrafter
  • 89
  • 1
  • 7