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');

});
6
  • You don't have an html element with the class show-toggle. Commented Nov 17, 2016 at 12:55
  • 1
    you are forget to add . in Show-toggle class and both class are different Show-toggle and show-toggle Commented Nov 17, 2016 at 12:55
  • Thanks. Edited, this was a typo in SO and not in my code. Commented Nov 17, 2016 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 ? Commented Nov 17, 2016 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. Commented Nov 17, 2016 at 13:09

1 Answer 1

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/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.