Last active
August 30, 2018 18:38
-
-
Save LegitDongo/f64487cc806297bcd3ca8afa5a0fc9a3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# How to use | |
# Required: 'image-switch' class on the image element | |
# Optional: | |
# 'image-switch-hover' class on the parent that you want to trigger the switch on hover | |
# data-replace-background-position - will replace the background position that is on the image on hover | |
# data-image-switch - will replace the image ('src' or 'background-image' auto detected) | |
# | |
# Example: | |
# <a href="#" class="image-switch-hover"> | |
# <div class="image-switch" data-replace-background-position="0 36px" | |
# style="width:38px;height:36px;background-image:url('spritesheet.png');background-position:0 0"></div> | |
# </a> | |
# For when you want to hover over an image and have it change without using css | |
$('.image-switch-hover, .image-switch-hover.image-switch').hover -> | |
that = $(@) | |
self = @ | |
if not that.is('.image-switch') | |
that = that.find('.image-switch') | |
self = that[0] | |
styles = window.getComputedStyle(self) | |
imageType = '' | |
if self.hasAttribute('src') | |
imageType = 'src' | |
else if styles.getPropertyValue('background-image') != 'none' | |
imageType = 'background-image' | |
else return | |
if not that.data('original-image') | |
imageSrc = '' | |
if imageType == 'src' | |
imageSrc = self.getAttribute('src') | |
else | |
imageSrc = styles.getPropertyValue('background-image') | |
that.data('original-image', imageSrc) | |
if not that.data('original-background-position') && styles.getPropertyValue('background-position') != '0% 0%' | |
that.data('original-background-position', styles.getPropertyValue('background-position')) | |
if self.hasAttribute('data-replace-background-position') | |
that.css { 'background-position': self.getAttribute('data-replace-background-position') } | |
if self.hasAttribute('data-image-switch') | |
if imageType == 'src' | |
that.attr 'src', self.getAttribute('data-image-switch') | |
else | |
that.css {'background-image': self.getAttribute('data-image-switch')} | |
, -> | |
that = $(@) | |
self = @ | |
if not that.is('.image-switch') | |
that = that.find('.image-switch') | |
self = that[0] | |
if self.hasAttribute('data-image-switch') | |
if self.hasAttribute('src') | |
that.attr 'src', that.data('original-image') | |
else | |
that.css {'background-image' : that.data('original-image')} | |
backgroundPosition = that.data('original-background-position') | |
if backgroundPosition | |
that.css { 'background-position': backgroundPosition } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment