Khushi
Khushi

Reputation: 1051

jquery does not change margin property.of a div

This is my first question on JQuery.

I have 3 Buttons. All are horizontally aligned like:

1st: Button                                      2nd: Button                                      3rd: Button

I have 1 div named popup.

If I click on button 1 the div should be shown like :

1st: Button                                      2nd: Button                                      3rd: Button

div: popup

If i click on 2nd button then it should be :

1st: Button                                      2nd: Button                                      3rd: Button

                                                               div: popup

For 3rd button :

1st: Button                                      2nd: Button                                      3rd: Button

                                                                                                                             div: popup

Using JQuery, I have selected the element. I calculate the margin-left of the button and store that in variable. I make the div invisible. Then I apply that margin to the div. And finally I make it visible. Here is the code.

<script>
    $('img').click(function () {
        var clickedImageMargin = $(this).css('margin-left');
        alert(clickedImageMargin);
        $('#popup').hide();
        $('#popup').css({ 'margin-left': clickedImageMargin + 100 });
        $('#popup').show();
    });
</script>

But div does not change its position. What might be the problem?

Upvotes: 0

Views: 108

Answers (2)

UweB
UweB

Reputation: 4110

The problem is that $(this).css('margin-left') returns a string, which is e.g. '200px' If you add 100 to that, string concatenation will be used, so you're setting a value of '200px100', which is invalid.

Upvotes: 1

dann
dann

Reputation: 853

var clickedImageMargin = $(this).position().left;

Upvotes: 1

Related Questions