Fuego DeBassi
Fuego DeBassi

Reputation: 3017

jQuery .width() detection

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>

Upvotes: 0

Views: 265

Answers (1)

Nick Craver
Nick Craver

Reputation: 630379

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.

Upvotes: 1

Related Questions