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

Navigating through a JSON object in JavaScript by employing regular expressions

Is there a way to extract the "Value" of elements "Data1", "Data2", "Data3", "Data4" from a JSON object without resorting to regex? I've heard that using regex with JSON is not recommended. <script> abc = { "model": { ... } } </script> ...

Delete the float attribute from the image when the inline-block is shifted to the bottom of the image

I have three elements in my design - a title, a paragraph, and an image. I want the image to float to the right, with the title and paragraph floating to the left and bottom, resembling "Image 1." To prevent the title from wrapping when narrowing the oute ...

I encounter difficulties using my static resources in the root route of my Express.js application

Can you guide me on how to implement styles and images from the assets folder in my webpage, specifically for the root route? As an example, I have a styles.css file located at assets/styles.css. In my code, I am using app.use(express.static('assets&a ...

React's Conditional Rendering

Let's imagine having these initial conditions: this.state = {plans: [], phase: 'daybreak'} along with a dynamic JSON object fetched from an API containing various schedules that may change periodically, for example: plans = {"daybreak": " ...

Converting a table into div elements and subsequently reverting it back to its original table format

[STOP DOWNVOTING: NEW AND IMPROVED] Discovering a simple technique on stackoverflow to transform tables into divs has been quite enlightening. By assigning classes to each tag, such as: <table class="table"> the process of converting from table to ...

Tips for showcasing all values in a nested array

In my Vue application, I am dealing with a nested array where users can select one date and multiple times which are saved as one object. The challenge I am facing now is how to display the selected date as a header (which works fine) and then list all the ...

Using ion-icon inside a clickable ion-card while applying float: right does not render properly

I am facing an issue with a list of ion-cards that have clickable icons appearing when you hover over them. The problem is that due to the floating nature of the icons, they are not positioned correctly (as shown in the image below) and end up getting cove ...

Filtering JSON data using jQuery

Is there a way to narrow down a Google Spreadsheet JSON (like the one found here: ) so that I only receive the json-entry where the field contains "title":{"type":"text","$t":"test1"} or in other words, "where title = test1". All I am looking for from the ...

Dynamically populate select options using Spring Boot Ajax technology

Hey everyone, I need some help with populating a select tag with a list of objects in JavaScript. Here's an example of the code: @RequestMapping(value="/getAllIndustries") @ResponseBody public List<IndustryModel>getAllIndustries() { return ...

Tips for updating the current image in the control navigation of the flexslider

I want to customize the control nav image to give it a unique appearance that corresponds to the slide image. Here's my JavaScript code: $(window).load(function() { $('#main-slider').flexslider({ animation: "fade", controlNa ...

Is the utilization of the React context API in NextJS 13 responsible for triggering a complete app re-render on the client side

When working with NextJS 13, I've learned that providers like those utilized in the React context API can only be displayed in client components. It's also been made clear to me that components within a client component are considered part of the ...

Array of dynamically typed objects in Typescript

Hello, I am a newbie to Typescript and I recently encountered an issue that has left me stumped. The problem I am facing involves feeding data to a Dygraph chart which requires data in the format [Date, number, number,...]. However, the API I am using prov ...

Leverage Bootstrap 4 for achieving flexible layouts and centering content with two elements using flex and justify-content

By using the d-flex, justify-content-center, and flex-grow-1 classes, I was able to achieve my desired layout with just 3 divs. <div class="row bg-primary d-flex justify-content-center"> <div class="col-auto"> LEFT </div> < ...

What could be the reason for the undefined initial state in my vuex store?

I am facing an issue with vuex-typescript where the initial state is always undefined. However, it works fine when I reset the state and refresh the window. Below is my setup for a simple module: import Vue from "vue"; import Vuex from "vuex"; import { m ...

Display/Conceal content with JQuery on a PHP webpage

I am having trouble with the following code. My intention is to show/hide the content between the #info id when clicking buttons, but nothing seems to be happening. Could you help me identify the issue? echo '<script> $( "#show' . $r ...

Tips for utilizing the for each function within a for loop

Looking to showcase prices alongside each product based on their unique sku value, I've put together a price list. An array of data is being iterated through and pushed into the div container. var arr = [ { "sku": "552", "title": "orange", "pric ...

How to Align a Footer to the Bottom of the Page using Bootstrap 5

My issue arises when using a dark background footer, as some pages lack enough content to fill the entire browser's viewport. Consequently, an unsightly white band appears below it. How can I ensure the footer reaches the bottom of the viewport on pa ...

Error: Trying to access the 'title' property of an undefined variable in Vue.js

Creating a replica of hackernews by utilizing the axios API. The NewItem.vue component is not receiving any data, resulting in an error — TypeError: Cannot read property 'title' of undefined. Can you identify what's causing this issue in t ...

Sharing information between controllers in OnsenUI using AngularJS and PhoneGap

I've encountered similar questions to mine that have been addressed, but I believe my scenario is unique. I began with the sample code available on this page for a basic app featuring a sliding menu integrated with Google Maps. My current project inv ...

Substitute for SendKeys() in Angular JS web pages using Selenium

Currently, I am utilizing selenium automation to streamline the processes of a third-party website. To input data into form fields, I have been employing the SendKeys() method. While this method is functional, it's time-consuming as there are numerous ...