0

I'm just wondering if there is a better way to detect the width for each of these .modal elements (there could be N number of them in that markup).

With the way I've got this figured now, it seems to only be using the .width() of the first .modal in the markup.

<script type="text/javascript">
    $(document).ready(function() {
        $(".modal").hide();
        $(".modal-links a").each(function(i,o){
          $(this).click(function(popUp){
            var modalWidth = $(".modal").width();
            var modalHeight = $(".modal").height();
            $(".modal").css({
             "margin-left":-(modalWidth/2) 
            });
            $(".modal:eq("+i+")").show().siblings(".modal").hide();
          });
        });
    });</script>

1 Answer 1

1

You want to get the .modal you want to deal with at the beginning of the .click(), like this:

$(document).ready(function() {
    $(".modal").hide();
    $(".modal-links a").each(function(i){
      $(this).click(function(popUp){
        var modal = $(".modal").eq(i),
            modalWidth = modal.width(),
            modalHeight = modal.height();
        modal.css({ "margin-left":-(modalWidth/2) })
             .show().siblings(".modal").hide();
      });
    });
});

Without doing this, you're correct it'll get the .height() and .width() of the first .modal element.

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

2 Comments

Awww... slow and wrong. Sometimes I just hate you @NickCraver :D But yeah, that was a pretty dumb mistake.
This works, but it seems like it might be calculating the width before the contents of the .modal div's are fully loaded (and therefore not the true width). Oh, and thanks BTW!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.