This unique script is designed to target elements with the class .trg
within the wrapping element identified by the id attribute id="wrap"
. When the mouse hovers over specific target elements, a timer starts running (currently set at 500ms). This time duration is stored in the variable var delay = 500
. After the specified time elapses, the script retrieves the data attribute of the target element and generates a new image element. Upon removing the mouse cursor from the target element, all elements with the class .img
are removed along with the created image.
By only loading content when it becomes visible, this approach improves site optimization and efficiency.
You can easily customize this code to add a class to an existing element or modify it according to your specific requirements.
Example:
$(document).ready(function () {
var delay = 500; // <-- delay time in ms
var wrp = '#wrap';
var mouseMove;
var url;
var el;
var show = true;
$(wrp + ' .trg').on('mouseenter', function () {
mouseMove = new Date().getTime();
show = true;
el = this;
url = $(this).attr('data');
});
$(wrp + ' .trg').on('mouseout', function () {
$('.img').remove();
});
setInterval(function () {
var curTime = new Date().getTime();
if (curTime - mouseMove > delay && $(wrp + ':hover').length != 0 && show) {
var img = document.createElement('img');
img.setAttribute('class', 'img');
img.setAttribute('src', url);
el.append(img);
show = false;
}
}, delay);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div id="wrap">
<div class="trg" data="https://blog.54ka.org/wp-content/uploads/2020/08/horses-on-summer-meadow_027_by_54ka-165x165.jpg">Lorem 01</div>
<div class="trg" data="https://blog.54ka.org/wp-content/uploads/2020/08/horses-on-summer-meadow_005_by_54ka-165x165.jpg">Lorem 02</div>
<div class="trg" data="https://blog.54ka.org/wp-content/uploads/2020/08/horses-on-summer-meadow_006_by_54ka-165x165.jpg">Lorem 03</div>
</div>
Example 2
This particular example illustrates how you can adapt the provided code to suit your needs.
$(document).ready(function () {
var delay = 500; // <-- delay time in ms
var wrp = '.hover-me';
var mouseMove;
var show = true;
$(wrp).on('mouseenter', function () {
mouseMove = new Date().getTime();
show = true;
});
$(wrp).on('mouseout', function () {
$('.img').removeClass('show');
});
setInterval(function () {
var curTime = new Date().getTime();
if (curTime - mouseMove > delay && $(wrp + ':hover').length != 0 && show) {
$('.img').addClass('show');
show = false;
}
}, delay);
});
.img {
display: none;
}
.show {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<p class="hover-me">Hi</p>
<img src="https://picsum.photos/150" class="img">