Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Help using jQuery to center an element horizontally and vertically over varying image dimensions.

  • This topic is empty.
Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #30666

    Hello, I’m creating an image gallery consisting of thumbnails with varying dimensions. I have created a hover effect that does a fadeIn so that a magnifying glass appears above the image indicating the image is enlargeable (in a modal window). However, I would like this magnifying icon to be positioned directly in the center of whatever image it is on. Lets take a look at my code….

    Markup (first ‘<' removed): ul class=”thumbnails”>
    li>
    a href=”#”>
    img src=”#” width: “150px” height:”200px”>
    /a>
    /li>

    li>
    a href=”#”>
    img src=”#” width: “320px” height:”200px”>
    /a>
    /li>
    /ul>

    Script:

    CSS:

    ul.thumbnails {
    width:100%;
    margin-top: 20px;
    overflow:hidden;
    }

    ul.thumbnails a span {
    display:none;
    background-image:url(../images_layout/magnifyingglass.png);
    background-repeat:no-repeat;
    width:50px;
    height:50px;
    position:absolute;
    }

    Could anyone help me out? I’m inexperienced with Jquery and don’t know what I’m doing wrong!

    #79440
    akeenlabs
    Participant

    It looks like the styling for the magnifier is based on a “span” tag but the span tag never gets created. In my tests, elem.append(“”) does not generate a span tag. Try this instead elem.append($(“<span />”)).

    Also, your “a” tags will probably need the “position: relative” style for their absolutely positioned children (i.e., the new span) to display correctly.

    Also, when calculating the left and top styles for the magnifier, you need to take into account the actual height and width of the magnifier. For example, left should be something like (this.outerWidth()/2)-(span.width()/2) and that value doesn’t need to be negative.

    Warning: I haven’t tested this all the way, so I hope it helps.

    #79027

    @akeenlabs – thanks for the comment. I was typing a response when I suddenly figured this out in css through good-ole’ firebug. I’m still using jQuery to append the tags and for the animations, but adjusted my css as follows;

    ul.thumbnails a span {
    display: none;
    background-image:url(../images_layout/magnifyingglass.png);
    background-repeat: no-repeat;
    width: 50px;
    height: 50px;
    position: absolute;
    margin-left: -25px; /* negative half of width to adjust for left 50% attribute*/
    left: 50%;
    margin-top: -25px; /* same idea as above */
    top: 50%;
    }

    Boy do I feel silly… over-complicating things once again.

Viewing 3 posts - 1 through 3 (of 3 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.