Ways to prevent image toggling when the mouse moves out of it or when the hover effect stops

I'm looking to toggle between two images on mouseover/hover and stop the toggling when hovering stops.

Here is the HTML code I have:

<div class="fader">
  <img src="image1" />
  <img src="image2" />
</div>

This is the JQuery code I'm using:

    $('.fader').hover(function() {
      toggleImage();
    });

function toggleImage() {
 if($('.fader').is(":hover")) {
  $('.fader').find("img").fadeToggle(1000);
  toggleImage();
 }
}

Some CSS for styling purposes:

.fader {
  display: inline-block;
}

.fader img:last-child {
  position: absolute;
  top: 0;
  left: 0;
  display: none;
}

The issue I'm facing is that I can't get the toggleImage() function to stop when the mouse is moved away or hovering stops.

I tried checking for :hover with the following code:

$('.fader').is(":hover")

But it didn't work as expected.

I need a way to stop the infinite loop of toggleImage() on mouseout or when hovering stops. Any suggestions?

If you need more help, check out this JSFiddle link.

Answer №1

Using only CSS:

* {
  margin: 0;
  padding: 0;
}
.fader {
  display: inline-block;
}
.fader img {
  transition: all .2s;
}
.fader img:last-child {
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0;
}

.fader:hover img:first-child {
  animation: toggle .5s infinite alternate .5s;
}
.fader:hover img:last-child {
  opacity: 1;
  animation: toggle .5s infinite alternate;
}

@keyframes toggle {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}
<div class="fader">
  <img src="http://placehold.it/200x200/fff000" />
  <img src="http://placehold.it/200x200" />
</div>

Answer №2

If you want to achieve a toggling effect using JavaScript, you can utilize the functions setInterval and clearInterval as shown in the example below:

var toggleTimer;

$('.toggler').hover(function() {
  toggleTimer = setInterval(toggleContent, 1000);
}, function() {
  clearInterval(toggleTimer);
});

function toggleContent() {
  $('.toggler').find(".content").toggle(1000);
}
.toggler {
  display: block;
}

.toggler .content:last-child {
  position: absolute;
  top: 0;
  left: 0;
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="toggler">
  <div class="content">Content A</div>
  <div class="content">Content B</div>
</div>

Answer №3

Here is a way you can attempt:

  $('.fader').on('mouseover', function() {
        toggleImage();
    });

    function toggleImage() {
        $('.fader').find("img").fadeToggle(1000);
      //toggleImage(); //You can omit this line
    }

Answer №4

let timer;
$('.fade-in-out').hover(function() {
    timer = window.setInterval(changeImage(), 2000);
});

function changeImage() {
     if($('.fade-in-out').is(":hover")) {
        $('.fade-in-out').find("img").fadeToggle(1000);
     } else {
        window.clearInterval(timer);
     }
};

Answer №5

To ensure the load effect in jQuery code works correctly, remember to include return false; after the function call.

$('.fader').hover(function() {
    toggleImage();
});

function toggleImage() {
$('.fader').find("img").fadeToggle(1000);
return false;
  toggleImage();
}
.fader { display: inline-block; }
.fader img:last-child {
    position: absolute;
    top: 0; 
    left: 0;
    display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 

<div class="fader">
    <img src="http://placehold.it/300x300/000fff" />
    <img src="http://placehold.it/300x300/fff000" />
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Assigning the style of the parent element based on the child element

Currently, I am attempting to develop a customized dropdown field and here is the code I have come up with: const list = document.querySelector('.list'); const listItems = list.getElementsByTagName('p'); document.querySelector('# ...

How AngularFire automatically adds back a removed item in a Firebase array

I have been working on a way to remove an item from my $firebaseArray called "boxes". Here is the "remove" function: function remove(boxJson) { return boxes.$remove(boxJson); } Although it gets removed, I noticed that it immediately reappea ...

Tips for navigating to an element with Nightwatch

I am currently using nightwatch for end-to-end testing of my application. One of the tests is failing because it seems unable to scroll to the element that needs to be tested. I am wondering if scrolling is necessary, or if there is another workaround. Her ...

Exploring object properties within arrays and nested objects using ReactJS

Within the react component PokemonInfo, I am looking to extract the stats.base_stat value from the JSON obtained from https://pokeapi.co/api/v2/pokemon/1/. The issue lies in the fact that base_stat is nested inside an array called stats. My assumption is t ...

Merge arrays values with Object.assign function

I have a function that returns an object where the keys are strings and the values are arrays of strings: {"myType1": ["123"]} What I want to do is merge all the results it's returning. For example, if I have: {"myType1": ["123"]} {"myType2": ["45 ...

The method continues to receive null values from Ajax despite successfully retrieving the data from Facebook

My current challenge involves creating a login using Facebook. The console indicates that the requested data (email, first_name, etc.) is being retrieved successfully, but for some reason, the AJAX request keeps sending null data to the PHP method. Below ...

Can you identify the mistake in this jQuery script?

My jQuery code seems to be causing issues as it's not working at all. According to Firebug, there is a missing parenthesis - but where could it be? $.get(url: 'example.html', function(data) { var $page = $(data); $page.filt ...

"Uncaught ReferenceError: $ is not defined in a JavaScript/Vue.js

Currently, I am working on the javascript/vue.js page found at this link. In this file, I have added the following code: $(document).ready(function() { myIP(); }); function myIP() { $.getJSON("//freegeoip.net/json/?callback=?", function(data) { / ...

Ways to stop users from inputting incorrect characters into an input field

I need help with restricting user input in a text field to only allow letters, numbers, and dashes (-). For alphanumerics only - "The alphanumeric character set includes numbers from 0 to 9 and letters from A to Z. In the Perl programming language, the un ...

What is the method to individually determine "true" or "false" using .map() in coding

I am faced with an array of data that needs to be manipulated individually, but it should still function as a cohesive unit. Can you assist me in achieving this? function OrganizeFollow() { const [followStatus, setFollowStatus] = useState([]); co ...

NextRouter does not have a property called "refresh"

Here is the provided code snippet: "use client"; import { useRouter } from "next/router"; import { useState } from "react"; export default function CreatePrompt() { const [title, setTitle] = useState(""); const ...

Enhancing the Appearance of Legends in Chartjs

I'm attempting to customize the legend in my Chartjs chart, but I'm facing an issue where I can't seem to change the font color. What I want to achieve is having the font color in white while keeping the individual item colors intact in the ...

Revamping Legacy React Native Projects with the Redux Toolkit

Is there a way to integrate redux toolkit with the existing store, reducer, and dispatch methods in my project without creating new ones? I am looking to update react-redux to the latest version. Please provide guidance and assistance. store.js ` import ...

What is the maximum size allowed for a background image in CSS?

Within a 70 by 50 px box, I have various SVG images with different aspect ratios - some portrait and others landscape. Setting background-size: 70px auto; works for landscape images but distorts the portraits by stretching them vertically. Is there a way t ...

What is the best way to spin an element around its center?

I'm faced with a challenge where I have an element that needs to be rotated using JavaScript. The rotation is currently functional, but it's rotating around points other than its center. My goal is to rotate the element around its own center. ...

The module specifier "logrocket" could not be resolved, make sure to use either npm or

I'm currently having an issue with initializing LogRocket. I followed the steps from the official documentation: I successfully installed it using node: npm i --save logrocket However, when trying to initialize it on my page earlier with: < ...

Unable to manipulate or customize the V-slot component

I recently implemented the v-flip feature on my Nuxt webpage, resulting in the following template: <div class="about__cards"> <vue-flip class="about__single-card" active-click width = "350px" height="450px"> <template v-slot:front> ...

Uncertain about the distinction between reducers and dispatchers when it comes to handling actions

I'm feeling a bit confused regarding reducers and dispatchers. While both receive actions as parameters, it doesn't necessarily mean that the actions I use in my dispatchers are the same as those used in my reducers, correct? For example, if I h ...

Asynchronous NestJs HTTP service request

Is there a way to implement Async/Await on the HttpService in NestJs? The code snippet below does not seem to be functioning as expected: async create(data) { return await this.httpService.post(url, data); } ...

Tips for adjusting the size and position of these div containers

My Steam Inventory Viewer is experiencing an issue with items with longer names. The div container becomes bigger than others, as seen in the demo on freegamekeys.info/trade or the image at http://prntscr.com/crpqk5. I am having trouble explaining my probl ...