Change jQuery animation when window resizes

On my website I use the following code to animate a hover action:

jQuery('#portfolio .project').hover( function() {
   // Animate icon
   jQuery(this).find('.overlay').animate({opacity:1.0, top:'75px'}, 300);
}, function() {
   // Hide icon
   jQuery(this).find('.overlay').animate({opacity:0, top:'155px'}, 300);
});

so that when the user hovers over a project an icon will be displayed as an overlay.

In this situation the image is 940px wide. But the website will be responsive, so is it possible to make this code variable depending on the window size of the browser? For example, when the browser width is 768px the icon will animate to 'top:100px' instead of 75px.

I've made a start with this, but have no idea how to go further.

jQuery(window).resize(function() {
   var window_width = jQuery(window).width();

Answers


Honestly, the easiest way for you is CSS.

Since your page is responsive, you already have different CSS styles for different window sizes. If you add an additional class and toggle that, you can easily set different values.

For your CSS:

/*
 * if the device width is bigger or equal to 768,
 * set the hover top property to 100px
 */

@media only screen and (min-device-width : 768px) {
    .overlay.hover {
        top: 100px;
    }
}

/*
 * if the device width is smaller or equal to 767
 * set the hover top property to 75px
 */

@media only screen and (max-device-width : 767px) {
    .overlay.hover {
        top: 75px;
    }
}

Then, all that remains is toggle class!

jQuery('.container').hover( function() {
    // Animate icon
    jQuery(this).find('.overlay').stop().toggleClass('hover', 300).animate({
        opacity: 1.0
    }, 300);
}, function() {
    // Hide icon
    jQuery(this).find('.overlay').stop().toggleClass('hover', 300).animate({
        opacity: 0.2
    }, 300);
});‚Äč

However, if you think this is too much effort (though it's much prettier), you can always just do it in javascript too:

var animatetop = getAnimateTop();

jQuery(window).resize(function() {
    animatetop = getAnimateTop();
});

jQuery('#portfolio .project').hover( function() {
    // Animate icon
    jQuery(this).find('.overlay').stop().animate({
        opacity: 1.0,
        top: animatetop + 'px'
    }, 300);
}, function() {
    // Hide icon
    jQuery(this).find('.overlay').stop().animate({
        opacity: 0,
        top:'155px'
    }, 300);
});

function getAnimateTop() {
    if(jQuery(this).width() >= 768) {
        return 100;
    } else {
        return 75;
    }
}

Need Your Help

Regarding communication between managed bean in JSF

jsf facelets

It seems I am not clear on my previous question about managed bean. So, I am posting it again in a more systematic manner.

Change iTunes Track Comment on MacOS

macos itunes

I've written the below code in vba to change comments in iTunes tracks in a Windows environment: