-3

I'd like to use a button to toggle some style on and off for some selected elements. I can add the style, like so:

$(".button").click(function() {
    $(".elements").each(function() {
        var height = $(this).data("height");
        $(this).css({ 'height': height, 'background-color': "#ccc" });
    });
 });

However, I'm not sure how to toggle the style to "off" (remove the styling I have just applied).

I've tried to use the following solution (jQuery toggle CSS?), but I'm not sure that it will work in this case as I'm using a function to gather a style attribute from within the data attribute of each element.

What would be the best way to do this with jQuery?

inersha
  • 422
  • 5
  • 20
  • To disable css you simply set the styles back to their default or desired values – JoshKisb Dec 22 '17 at 15:13
  • Possible duplicate of [jQuery toggle CSS?](https://stackoverflow.com/questions/3337621/jquery-toggle-css) – JoshKisb Dec 22 '17 at 15:16
  • This is old-school way for toggling: https://jsfiddle.net/e9popoet/1/ However, not sure about default style (and where it is defined)...maybe all could be simplified. – sinisake Dec 22 '17 at 15:30
  • @sinisake you can just do `flag = !flag` at the end of the loop – JoshKisb Dec 22 '17 at 15:48

1 Answers1

-1

You are making it unnecessarily complex. Just set a default style, then toggle a class with a different styling. See the example below.

$(function () {

$("[type=button]").click(function () {

$("div").toggleClass("otherClass");

});
});
* {
margin: auto;
width: 100px
}

div {
height: 100px;
background: red;
margin-bottom: 25px;
transition: all 2s;
color: white;
line-height: 100px;
text-align: center;
font-weight: bold;
}

.otherClass {
background: green;
transition: all 2s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>The DIV</div>

<input type="button" value="Toggle Style" >
Sleek Geek
  • 4,638
  • 3
  • 27
  • 42
  • There is one problem - height is defined in data attribute, for each element, so every element will have different height... – sinisake Dec 22 '17 at 15:46
  • @sinisake In that case, the height should be left as is. Am I missing anything? – Sleek Geek Dec 22 '17 at 15:51
  • Thanks, but as mentioned, I'm looking to set a variable height on each element using a value from the data attribute. There is no height beforehand, but the height is added after clicking the button. – inersha Dec 22 '17 at 15:51
  • @inersha I think you should provide more information! – Sleek Geek Dec 22 '17 at 17:04