On mouseout stop setInterval - javascript

I'm trying to create a simple image rotator on hover effect. It working properly on mouse hover, but doesn't work when mouse out method.
var imgFlip = $("img").data( "flip" );
var imgOriginal = $("img").data( "original" );
var images = imgFlip.split(/,|, |;|; /);
var index = 0;
function rotateImage()
{
$('.img-rotator').fadeOut('fast', function()
{
$(this).attr('src', images[index]);
$(this).fadeIn('fast', function()
{
if (index == images.length-1)
{
index = 0;
}
else
{
index++;
}
});
});
}
$(document).ready(function()
{
$('.img-rotator')
.mouseover(function () {
var refreshIntervalId = setInterval (rotateImage, 1000);
})
.mouseout(function () {
$(this).attr('src', imgOriginal);
})
});
Jsfiddle example here - https://jsfiddle.net/wbz35L68/15/
Thank you for any advice

You need to clear the setInterval on mouseout. I also reworked some of your code to clean things up and cache refs. You should also use mouseenter and mouseleave for this.
$(document).ready(function(){
// cache selector
var rotator = $('.img-rotator'),
// grab all data
data = rotator.data(),
// ref flip
imgFlip = data.flip,
// ref original
imgOriginal = data.original,
// get image urls
images = imgFlip.split(/,|, |;|; /),
// start index
index = 0,
// ref interval
refreshIntervalId = null;
function rotateImage(){
rotator.fadeOut('fast', function(){
$(this)
.attr('src', images[index])
.fadeIn('fast', function(){
var last = index === images.length - 1;
index = last ? 0 : index + 1;
});
});
}
rotator
.mouseenter(function(){
refreshIntervalId = setInterval(rotateImage, 1000);
})
.mouseleave(function(){
// clear interval and set null
clearInterval(refreshIntervalId) && (refreshIntervalId = null);
$(this).attr('src', imgOriginal);
})
});
.container {
margin-top: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col">
<img class="img-rotator" data-flip="http://www.snorkl.tv/dev/loaderMax/images/bird.png, http://www.snorkl.tv/dev/loaderMax/images/whale.png" data-original="http://www.snorkl.tv/dev/loaderMax/images/crab.png" src="http://www.snorkl.tv/dev/loaderMax/images/crab.png" width="320" height="200"/>
</div>
</div>
</div>

Related

I want to make an image appears when I hover over text. I integrated few JavaScripts but it's still not working

I want to show an image but still I can't manage to make it works. Respective parts I need are there like.
function mouseIn() {
$('.img').addClass('show');
}
function mouseOut() {
$('.img').removeClass('show');
}
$('.hover-me').hover(mouseIn, mouseOut);
.img {
display: none;
}
.img.show {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="hover-me">Hi</p>
<img src="https://picsum.photos/150" class="img">
This script takes the .trg class elements that are in the packaging element id="wrap". When you hold the mouse over some target elements it starts to run time (I have currently set 500ms). The time is set to the variable var delay = 500. When this time expires, the script takes the data attribute of the target element and creates a new element img. When you remove the mouse cursor from the target element, all elements with class .img are removed... thus the created image is removed.
For site optimization, this method is better because you will not load content that is invisible... but you will create it when needed.
With small adjustments to my code, you can change it to add a class to an existing element or work in another way that works for you.
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 example is based on your code
$(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">

Image auto swapping script doesnt show image most of the time?

I have the following script running to rotate between two of my logos.
What i am trying to do is the page will load and then the image will begin to rotate directly to the other image with out blank.
Here is the code:
var logo1 = "logo2.png";
var logo2 = "logo1.png";
var images = new Array (logo1, logo2);
var index = 1;
function rotateImage()
{
$('.logoimage').fadeOut('slow', function()
{
$(this).attr('src', images[index]);
$(this).fadeIn('fast', function()
{
if (index == images.length-1)
{
index = 0;
}
else
{
index++;
}
});
});
}
$(document).ready(function()
{
setInterval (rotateImage, 5000);
});
<img class="logoimage" src="logo1.png" onmouseover="this.src='logo2.png'" onmouseout="this.src='logo1.png'" alt="Dear Leader" style="display: inline;">
Instead to use onmouseover and onmouseout you can use the jQuery hover.
While you are in the hovering function you have to stop the timer fading effects, in order to avoid the blinking effect.
My proposal is:
var logo1 = "https://ac3d197e9505f18c50e0-32b9f49f48b2c22be12b40ee79e2acc4.ssl.cf1.rackcdn.com/icon/logos_and_badges_thumbs_up/7x5uDqD4GBTrCSbXggZ-/58C79CAE-C3E6-4D6A-BAF5-A03631274FD7.png";
var logo2 = "https://www.facebookbrand.com/img/assets/asset.f.logo.lg.png";
var images = new Array (logo1, logo2);
var index = 1;
var onHovering = false;
function rotateImage() {
if (onHovering) {
return; // prevent fading while hovering...
}
$('.logoimage').fadeOut('slow', function() {
$(this).attr('src', images[index]);
$(this).fadeIn('fast', function() {
if (index == images.length-1) {
index = 0;
} else {
index++;
}
});
});
}
$(function () {
setInterval (rotateImage, 1000);
$('.logoimage').hover(function() {
onHovering = true;
$(this).attr('src', images[0]);
}, function() {
onHovering = false;
$(this).attr('src', images[1]);
});
});
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<img class="logoimage" src="https://www.facebookbrand.com/img/assets/asset.f.logo.lg.png" alt="Dear Leader" style="display: inline;">

How to interchange between 2 logos?

I have the following code:
var logo1 = "//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_2x.png";
var logo2 = "//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_hover_2x.png";
var images = new Array (logo1, logo2);
var index = 1;
function rotateImage()
{
$('.logoimage').fadeOut('fast', function()
{
$(this).attr('src', images[index]);
$(this).fadeIn('fast', function()
{
if (index == images.length-1)
{
index = 0;
}
else
{
index++;
}
});
});
}
$(document).ready(function()
{
setInterval (rotateImage, 5000);
});
var images = new Array (logo2);
var index = 1;
function rotateImage()
{
$('.logoimage').fadeOut('fast', function()
{
$(this).attr('src', images[index]);
$(this).fadeIn('fast', function()
{
if (index == images.length-1)
{
index = 0;
}
else
{
index++;
}
});
});
}
$(document).ready(function()
{
setInterval (rotateImage, 5000);
});
Its working well apart from the following bugs:
Image loads even though image already is showing on page.
I have an image onmousehover effect on that image and its causing bad effect.
Is it possible to interchange between the image src and the img onmousehover src?
Thanks
Alex
you can change the src of the img tag using JavaScript as below,
function hover(element) {
element.setAttribute('src', '//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_2x.png');
}
function unhover(element) {
element.setAttribute('src', '//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_hover_2x.png');
}
and the html be
<img id="my-img" src="http://dummyimage.com/100x100/000/fff" onmouseover="hover(this);" onmouseout="unhover(this);" />
After Edit :
If you want to change it on some timeout, You need to put your below code inside window.onload = function() {}
var images = new Array();
images[0] = "logo_1.png";
images[1] = "logo_2.png";
var images = new Array();
for (var i = 0; i < 2; i++) {
images.push("logo_" + i + ".png");
}
var x = 0;
function changeImage() {
document.getElementById('ad').src = images[x];
if (x < 8) {
x += 1;
} else {
x = 0;
}
if (window.addEventListener) {
window.addEventListener('load', changeImg, false);
}
function changeImg() {
var x = 0;
setInterval(function() {
changeImage()
},5000);
}
HTML:
<img id="ad" src="//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_2x.png" />
Use jQuery hover to run code when hovering in or out of an element. Also use setTimeout to run code after a delay.
var logo1 = "//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_2x.png";
var logo2 = "//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_hover_2x.png";
$(function() {
$('.logoimage').hover(function() {
setTimeout(function() {
$('.logoimage').attr('src', logo2);
}, 1000);
}, function() {
setTimeout(function() {
$('.logoimage').attr('src', logo1);
}, 1000);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img class="logoimage" src="//cdn.shopify.com/s/files/1/0816/3411/t/3/assets/logo_2x.png">

Jquery - add function to jquery

Hey there i got this fiddle :
http://jsfiddle.net/5H5Xq/42/
containing this jquery:
function anim(selector) {
$(".images img", selector).first().appendTo($('.images', selector)).fadeOut(2000);
$(".images img", selector).first().fadeIn(2000);
}
// Untuk delay gambarnya
var i = 0, max = 3;
myFunction = function(event){
$(".subbox1").each(function() {anim(this)});
i += 1;
if(i >= max) { i = 0; }
}
var interval = setInterval(myFunction, 5000);
$(".slider").hover(function() {
clearInterval(interval);
var img = $('<img>');
img.attr('src', $(this).attr('data-url'));
$('#newImage').html(img);
$('.images').hide();
return false;
i += 1;
$(".subbox1").each(function() {anim(this)});
});
$(".slider").mouseout(
function (){
$('.images').show();
// $('#newImage').hide();
interval = setInterval(myFunction, 5000);
}
);
It just means:
Every 5 seconds => automatic image-change.
When i hover throw a link => image-change + automatic image change disabled.
What i wanted to add to the automatic image-change:
Depending on the current picture, the -item gets a new background-color..is this possible?
greetings
Sure you can. Just change the background-color css attribute of the element depending on your criteria.
if (*your criteria here*) {
element.css("background-color", "#ff0000");
}

jquery stop image rotation on mouseover, start on mouseout / hover

I have built a jQuery rotator to rotate through 3 divs and loop them. I would like to add the functionality on mouse over to "freeze" the current div and then start again on mouse out.
I've thought about setting a variable to false at the start of the function and setting it true when it's on it's current frame but I've got my self a bit confused.
I've also tried to use the hover function but when using the in and out handlers, I'm confused as to how to stop, restart the animation.
function ImageRotate() {
var CurrentFeature = "#container" + featureNumber;
$(CurrentFeature).stop(false, true).delay(4500).animate({'top' : '330px'}, 3000);
var featureNumber2 = featureNumber+1;
if ( featureNumber == numberOfFeatures) {featureNumber2 = 1}
var NewFeature = "#container" + featureNumber2;
$(NewFeature).stop(false, true).delay(4500).animate({'top' : '0px'}, 3000);
var featureNumber3 = featureNumber-1;
if ( featureNumber == 1) {featureNumber3 = numberOfFeatures};
var OldFeature = "#container" + featureNumber3;
$(OldFeature).stop(false, true).delay(4500).css('top' , '-330px');
setTimeout('if (featureNumber == numberOfFeatures){featureNumber = 1} else {featureNumber++}; ImageRotate2()', 7500)};
Any help would be greatly appreciated!!
Thanks, Matt
If you were to add this code:
var timerId = null;
function startRotation() {
if (timerId) {
return;
}
timerId = setInterval('if (featureNumber == numberOfFeatures){featureNumber = 1} else {featureNumber++}; ImageRotate2()', 7500);
}
function stopRotation() {
if (!timerId) {
return;
}
clearInterval(timerId);
timerId = null;
}
and replace the last line of your code block with a simple call to startRotation();, then you could call stopRotation and startRotation when the mouse hovers over/leaves your element:
$('your-element-selector').hover(stopRotation, startRotation);
It's not clear what you are trying to do with the three divs without seeing the HTML and more code, so I think a basic example might help you better (demo).
HTML
<div class="test">image: <span></span></div>
Script
$(document).ready(function(){
var indx = 0, loop, numberOfFeatures = 5;
function imageRotate(){
indx++;
if (indx > numberOfFeatures) { indx = 1; }
$('.test span').text(indx);
loop = setTimeout( imageRotate , 1000 );
}
imageRotate();
$('.test').hover(function(){
clearTimeout(loop);
}, function(){
imageRotate();
});
})
changed things up a little bit, here is how I ended up doing it. `
var animRun = false;
var rotateHover = false;
function startRotation() {
rotateHover = false;
ImageRotate();
}
function stopRotation() {
rotateHover = true;
clearTimeout();
}
function ImageRotate() {
if (rotateHover == false){
animRun = true;
var CurrentFeature = "#container" + featureNumber;
$(CurrentFeature).stop(false, true).animate({'top' : '330px'}, featureDuration, function(){animRun = false;});
var featureNumber2 = featureNumber+1;
if ( featureNumber == numberOfFeatures) {featureNumber2 = 1}
var NewFeature = "#container" + featureNumber2;
$(NewFeature).stop(false, true).animate({'top' : '0px'}, featureDuration); /* rotate slide 2 into main frame */
var featureNumber3 = featureNumber-1;
if ( featureNumber == 1) {featureNumber3 = numberOfFeatures};
var OldFeature = "#container" + featureNumber3;
$(OldFeature).stop(false, true).css('top' , '-330px'); /*bring slide 3 to the top*/
//startRotation();
setTimeout('if (featureNumber == numberOfFeatures){featureNumber = 1} else {featureNumber++}; if (rotateHover == false){ImageRotate2()};', featureDelay);
};
};

Categories

Resources