Using jQuery to adjust "transform: translate3d" based on container width

I'm using the following jQuery to adjust the height of a div based on its width:

<script type="text/javascript">
    jQuery(window).bind("load resize",function(e){
      jQuery(".showcase .image_container").css('height', jQuery(".showcase .image_container").width()/'1.7438');

This is working well but I'd like to use "transform: translate3d" to move the image inside this div up on hover:

.showcase .image_container:hover img { transform: translate3d(0px, -150px, 0px); }

How can I use jQuery to adjust the Y value (150px) based on the width of the .image_container. i.e.

.image-container width / 3.2667


Answers 1

  • You can attach an event handler for mouseover/mouseout and do what you need within that.

    See this jsFiddle demo.

    Relevant code is:

    var timerID;
    $('.showcase .image_container img').on('mouseover', function () {
        $(this).css('transform', 'translate3d(0px, -' + $('.showcase .image_container img').width()/3.2667 + 'px, 0px)');
    }).on('mouseout', function (e) {
        var self = this;
        timerID = setTimeout(function () {
            $(self).css('transform', 'translate3d(0px, 0px, 0px)');
        }, 1000);

    Why the setTimeout()? Otherwise, you run into the problem of the mouseout triggering when the image moves up and the cursor out of it.

Related Articles