0

I am toggling (.red) class via Jquery on a button click. And when the element has the class red I need to give it a margin-top (say a 50px) dynamically via JQuery and not in the class by default. The toggling works fine but not the adding of Margin Top: Code Below with link to fiddle. What am I missing?

$('button').click(function() {
    $('.demo').toggleClass('red');
    $('.red').css('margin-top','10px');
});

[Fiddle] http://jsfiddle.net/vineetgnair/wb3jd3vn/1/

Thank you all.

3
  • Have a look at the api of jquery, esspecially read about selectors. The definition $.('red') means: find all HTML elements with the id "red" and add an style attribut to them (with "margin-top: 10px"). Commented Sep 1, 2014 at 9:23
  • It is taking the margin also. If you want to increase the margin every time it takes red class then use this line $('.red').css('margin-top', $('.demo').css('margin-top') + 10); instead of $('.red').css('margin-top','10px'); Commented Sep 1, 2014 at 9:27
  • actually I want to toggle margin too.. when its red there should be a margin-top of 10px and when yellow the margin-top should be back to 0. I guess I forgot this to mention in the Post. Commented Sep 1, 2014 at 9:31

1 Answer 1

3

The margin is getting set, but you need to make it visible in such a way that it has to clear the margins not collapsing. For your view, I have added a border to show the visibility:

body {overflow: hidden;}

Also, it is better to use the same jQuery object!

$('button').click(function() {
    $('.demo').toggleClass('red').css('margin-top','10px');
});

Fiddle: http://jsfiddle.net/wb3jd3vn/4/

The above code will always add only one margin of height 10px! If you want to increase the margin every time when the user clicks, you need to do this:

$('button').click(function() {
    $('.demo').toggleClass('red').css('margin-top', parseInt($('.demo').css('margin-top').substring(0, ($('.demo').css('margin-top').length - 2))) + 10 + "px");
});

Fiddle: http://jsfiddle.net/praveenscience/wb3jd3vn/9/

If you need to just toggle the margin, you can set it in the .red class:

.demo.red {margin-top: 10px;}

And just reduce your code to:

$('button').click(function() {
    $('.demo').toggleClass('red');
});

Fiddle: http://jsfiddle.net/praveenscience/wb3jd3vn/10/

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

2 Comments

actually I want to toggle margin too.. when its red there should be a margin-top of 10px and when yellow the margin-top should be back to 0. I guess I forgot this to mention in the Post..
thanks for this.. but i need to toggle the margin between 10 and 0 not increase it by 10 evertime...but this is a new code to me thanks..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.