How can I switch between different images using jQuery?

HTML

<div class="image_rollover">
     <img id="image_one" src=image_one.png">
     <img id="image_two" src="image_two.png">
     <img id="image_three" src="image_three.png">
     <img id="image_four" src="image_four.png">
     <img id="image_five" src="image_five.png">
     <img id="image_six" src="image_six.png">
</div>

CSS

.image_rollover{
    border:1px solid #000000;
    width:130px;
    height:80px;
    overflow:hidden;
}

Script

This script will change the images one by one when hovering over the div.
$(document).ready(function(){
    $("#image_two, #image_three, #image_four, #image_five, #image_six").hide();

    $(".image_rollover").hover(function(){
      $(this).find("#image_one, #image_two, #image_three, #image_four, #image_five, #image_six").toggle();
    });
});

Upon hovering over the div, the images should change sequentially from "image_one" to "image_six". Any suggestions on how to implement this feature effectively?

Answer №1

http://example.com/code-sample

$(document).ready(function () {
    $("#image_two, #image_three, #image_four, #image_five, #image_six").hide();

    $(".image_rollover").hover(function () {
       animateFunction()
    });
});

function animateFunction() {
    var $curr=$(".image_rollover img:visible");
    var $next=$curr.next();    

    if($next.size()==0) $next=$(".image_rollover img:first");

    $next.show();
    $curr.hide();
}

or something similar

UPDATE

http://example.com/updated-code

var hover=false;
var interval;

$(document).ready(function () {
    $("#image_two, #image_three, #image_four, #image_five, #image_six").hide();
    $(".image_rollover").hover(function () {
       hover=true;
       animateFunction()
    },function(){
        hover=false;
        clearTimeout(interval);
        $(".image_rollover img:visible").hide();
        $(".image_rollover img:first").show();
    });
});

function animateFunction() {

    if(hover==false) return;

    var $curr=$(".image_rollover img:visible");
    var $next=$curr.next();    

    if($next.size()==0) $next=$(".image_rollover img:first");

    $next.show();
    $curr.hide();

    interval=setTimeout(function(){ animateFunction(); }, 1000);
}

Answer №2

$(document).ready(function(){
    $('.image_rollover img').hide();
    var count = 0;
    var $imageRollover = $('.image_rollover');
    var totalImages = $imageRollover.find('img').length;
    $imageRollover.on('mouseenter', function(){
        $('.image_rollover img').hide();        
        console.log(count);
        $imageRollover.find('img').eq(count).show();
        count++;
        if (count >= totalImages) {
            count = 0;
        }
    });
});

To view the working example, visit http://jsfiddle.net/2q2ycbdz/2/

Answer №3

It is recommended to use CSS to hide images and simplify the image selector within a div container (or group them with a class).

Take a look at this:

JS

$(document).ready(function(){
  $(".image_rollover").hover(function(){
    $(this).find("img").toggle();
  });
});

CSS

.image_rollover{
  border:1px solid #000000;
  width:130px;
  height:80px;
  overflow: hidden;
}

.image_rollover img{
   display: none;
}

HTML

<div class="image_rollover">
  <img id="pic_one" src=image_one.png">
  <img id="pic_two" src="image_two.png">
  <img id="pic_three" src="image_three.png">
  <img id="pic_four" src="image_four.png">
  <img id="pic_five" src="image_five.png">
  <img id="pic_six" src="image_six.png">
</div>

See it in action on codepen.

Answer №4

JavaScript

$(document).ready(function(){
    let currentFrame = 1;
    $('.image_rollover').hover(function(){
        $('.image_rollover img').hide();
        $('.image_rollover img:nth-child('+currentFrame+')').show();
        currentFrame++;
        if (currentFrame == 7)
            currentFrame = 1;
    },function(){});
});

Answer №6

If you're in search of some animated effects, give this a try.

      $(document).ready(function () {

            var $siblings = $("#image_one").siblings();
            $siblings.hide();

            $("#image_one").on("mouseenter", function () {
                var timer = 100;
                var showTime = 0;
                $siblings.each(function () {
                    showTime += timer;
                    $(this).fadeIn(showTime).show()
                })
            });
        });

Alternatively, if you prefer a chain-like animation:

Hover over the first image to reveal the second, then hover over the second for the third and so on... Does this meet your requirements?

        $(document).ready(function () {

            var $siblings = $("#image_one").siblings();
            $siblings.hide();
            var timer = 500;
            var showTime = 0;
            function init_chain(ev){
                showTime += timer;
                var $next_element = $(ev.target).next()
                $next_element.fadeIn(showTime).show();
                $next_element.bind("mouseenter",init_chain);
            };

            $("#image_one").on("mouseenter", function (event) {
                init_chain(event);
            });
        });

Let us know if this works for you!

Thanks a lot!

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

Update the HTML weather icon with data from JSON

I have a collection of weather icons stored on my computer. How can I customize the default weather icons with my own set of icons? In the JSON file, there is a variable like this: "icon":"partlycloudy" <html> <head> <script src="http://c ...

Reorganize a list based on another list without generating a new list

Among the elements in my HTML list, there are items with text, input fields, and tables. I also have a specific order list like [3,1,2,0]. Is it feasible to rearrange the items in the HTML list on the page based on this order list without generating a new ...

"The controller's $scope isn't being updated within the DIV following a routing change

My website contains ng-view partials that change based on routing updates in $routeProvider. anmSite.config(function($routeProvider, $locationProvider){ $locationProvider.html5Mode(true); $routeProvider //Home page route .when("/", { temp ...

How can I access the id_lang variable in React JS from outside its scope?

How do I access the 'id_lang' variable outside of the render function in order to pass it down for checking? const Navbar = () => { const getID = async (id) => { let id_lang = id; console.log(id_lang); } ret ...

jQuery slideToggle effect causes neighboring elements to move

After clicking on the element I've set as the trigger for slideToggle, it moves a few pixels to the right without any apparent cause. It seems like there might be an issue with the CSS, but I'm having trouble pinpointing the exact problem. You c ...

Issue tracking the window scroll in Internet Explorer when using Jquery animation

Is there a way to make a div follow the window's scroll position smoothly? It seems to work fine in Firefox, but in Internet Explorer 6 and 7, the animation causes a jumpy effect with the window scrolling. I've attempted to use easing without su ...

Looking to customize scrolling behavior when navigating back in Next.js?

I have a function in my index.js file that fetches a list of posts like this: const Index = (props) => { return ( <div> {props.posts.map((each) => { return ( <Link scroll={false} as ...

Stop HTML <dialog> from automatically closing using Vue

I'm working on a project where I need to use Vue to programmatically prevent an HTML dialog element from closing when the close event is triggered. Here's the code snippet I am currently using: import {ref} from 'vue'; const dialogTe ...

What is the issue with retrieving HTML from an iframe in Internet Explorer when the contents are

Here is the script I used to generate an iframe: Ifrm = document.createElement("IFRAME"); document.body.appendChild(Ifrm); IfrmBod = $(Ifrm).contents().find('body'); IfrmBod.append('<p>Test</p>'); The jQuery function for a ...

Adjusting the size of a Vue component on the fly

I'm struggling to find a way to dynamically adjust the width of a component. The component I am working with is called 'vue-burger-menu' -> https://github.com/mbj36/vue-burger-menu. To set the width, you need to assign a number to the prop ...

What is the best way to showcase the array data of two description values in a Vue v-for loop?

An array called ledgerDetails contains 32 data elements. These details are displayed in a vue v-for loop. However, within the loop, I need to show specific details from invoiceDescriptions (23 data elements) and paymentDescriptions (1 ...

Tips for retrieving arguments within a method called from a template in vue.js?

Here is an example where I am attempting to call a method from the template and pass in some arguments. How can I access those arguments from within the method? Snippet from script: methods: { showBinaries(job, id) { let test_url = process.en ...

Conceal the object, while revealing a void in its place

Is there a way to hide an image but keep the containing div blank with the same dimensions? I want it to appear as if no content was there, maintaining the original width and height. For example: http://jsfiddle.net/rJuWL/1/ After hiding, "Second!" appea ...

Encountering a TypeError while trying to run Pythonshell on my Mac device

When I run a python script in node.js using python shell, it works perfectly on my Windows system. However, I encounter an error when trying to run the same thing on my Macbook: Error: TypeError: can't multiply sequence by non-int of type 'float ...

Develop a monitor for an entity that has not been created

Currently, I am tackling a feature that involves tracking an asynchronous request within a synchronous one. Let me elaborate. The code snippet I am working with looks something like this: const myObj = {}; function sendMessage(requestId, data) { kafkaP ...

When trying to access a URL in a next.js application using the fetch() function, the router encountered an

I recently started working on a frontend project using Next.js v13.4 app router, with an additional backend. I have organized my routes and related functionalities in the api folder within the app directory. However, when I attempt to use the fetch() funct ...

Effective methods to prevent the `translate` transform from triggering an element to be perceived as position relative?

I am encountering an issue with an absolutely positioned div that is nested within a statically-positioned parent container. I noticed that when I apply the transform: translateY(-50%) property to the container, the child element behaves as if it were bein ...

Guide on setting checkbox to be checked or unchecked depending on a value during table creation

Displaying records is dependent on the response from the server. The checkbox status should be determined by the value of appUserID. appUserID can either be 1 or 0. If appUserID is 1, check the checkbox; otherwise leave it unchecked. Please advise on h ...

The JavaScript object is not being properly posted to the $_POST variable on the PHP page when using vanilla AJAX

Despite my extensive search on the internet and stackoverflow, I have yet to find a solution to my problem. While I understand that JQuery is effective in sending objects, when attempting the same task without the framework, my posts fail to go through to ...

Styling elements with CSS

I've been attempting to align a button to the right of another button. The example above illustrates what I'm trying to achieve. I used Bootstrap to build it, which has a useful navbar feature for layout. However, despite my efforts to use right ...