Skip to content

Instantly share code, notes, and snippets.

@omargfh
Last active December 24, 2020 07:34
Show Gist options
  • Save omargfh/81227bc21166d49c6e081cb24cf76005 to your computer and use it in GitHub Desktop.
Save omargfh/81227bc21166d49c6e081cb24cf76005 to your computer and use it in GitHub Desktop.
Hover-to-expand Effect in jQuery
<div class="flex">
<div class="show-gallery-item-on-hover"></div>
<div class="gallery-item" id="gallery-item-first">
<img src="https://via.placeholder.com/350x250/0000FF/808080%20" alt="placeholder">
</div>
<div class="gallery-item" id="gallery-item-second">
<img src="https://via.placeholder.com/350x250" alt="placeholder">
</div>
<div class="gallery-item" id="gallery-item-third">
<img src="https://via.placeholder.com/350x250/FF10A8/202020%20">
</div>
</div>
$(document).ready(function() {
$('.gallery-item').each(function(i, el) {
$(el).mouseover(function() {
// Extract data
var src = this.innerHTML;
var update = $('.show-gallery-item-on-hover');
update.html("");
// Calculate new position
pos = $(el).offset();
pos.right = Math.round(pos.left + $(el).width());
pos.bottom = Math.round($(el).height() + pos.top);
pos.width = $(el).children().prop('naturalWidth');
pos.height = $(el).children().prop('naturalHeight');
pos.midY = (pos.top + pos.bottom) / 2;
pos.midX = (pos.left + pos.right) / 2;
pos.newY = pos.midY - pos.height / 2 >= 0
? pos.midY - pos.height / 2 : 0;
pos.newX = Math.round(pos.right - $(window).width()) >= -20 ?
pos.right - pos.width : pos.midX - pos.width / 2 >= 0 ?
pos.midX - pos.width / 2 : 0;
// Update elements
update.html(src);
update.css({
top: pos.newY,
left: pos.newX,
zIndex: 1031,
boxShadow: "0px 0px 10px rgba(32, 32, 32, 0.6)",
opacity: 0
});
update.animate({
opacity: 1
}, 600);
setTimeout(()=> {
$('.show-gallery-item-on-hover').mouseleave();
}, 30000);
});
$('.show-gallery-item-on-hover').mouseleave(function(event) {
this.innerHTML = "";
});
});
});
* {
box-sizing: border-box;
font-family: 'PT Sans', sans-serif;
font-size: 20px;
font-weight: bold;
margin: 0px;
padding: 0px;
}
.flex {
display: flex;
flex-direction: row;
}
.gallery {
width: 220px;
height: 220px;
background-color: rgba(32, 32, 32, 0.5);
}
.gallery-item {
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
position: relative;
width: 100%;
height: 100%;
}
.show-gallery-item-on-hover {
position: absolute;
margin-left: 0;
margin-top: 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment