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

What could be causing my website to function flawlessly in Firefox but not in Chrome or Internet Explorer?

Hey everyone, I'm feeling lost and have been comparing files using DiffNow. I don't have any code to offer because I'm unsure of where to even begin. The website is coded in php/html/mysql/jquery. Here are my main concerns: -Animations are ...

Testing NodeJS Database Functionality using Mocha and Asserting with should.js

Currently, I am in the process of testing my NodeJS application using mocha and should. The issue I am facing is that while the first test executes smoothly, the second one fails with an error of null. Interestingly, both tests result in a valid user being ...

Creating a persistent hover effect

Utilizing primarily CSS, along with background images and adjacent selectors, I am creating a page that displays unique human-readable text information when the user hovers over horizontally stacked images. The textual information is presented in a div on ...

Exploring the differences between the meta viewport and font size

My website includes the following code in the section: <meta name="viewport" content="width=990"/> This setting helps to display my webpage well on mobile devices, as using width=device-width causes issues with elements that have 100% width. Howeve ...

Managing the transition of the object in question

I am in the process of designing a navigation bar. I have created an array to store the information of the tabs present in the nav bar. tabs: [ { name: 'All',id: "dash.courses.all", to: 'all', curre ...

Is HTML5 Device Orientation the answer to a dependable compass system?

I am currently developing a project for mobile web that requires access to the compass direction of the user's device. At the moment, my code is quite basic, but here is what I have: var updateDirection = function (evt) { $("#dire ...

Preventing the mysql server called by php from running when the website is refreshed

My local website runs by querying a mysql database using inputs from an html form. The form values are passed to php via jQuery to execute the query. Is there a way to send a command to the mysql server to terminate the query if the web page is refreshed? ...

What is the best way to retrieve the 'items' data stored in this list?

I am working with a list of data that includes 6 categories - bags, shoes, girls, boys. Each category contains the same type of data like id, items (with properties: desc, id, imageUrl, name, price), routeName, and title. My goal is to loop through all ca ...

Exploring the Collapse and Dropdown features in Bootstrap 5 Navbar

Struggling with my navbar on Bootstrap 5 - the collapse feature isn't working after expanding, and the dropdown list fails to drop down. <!-- Using Bootstrap-5 --> <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-pro ...

Switching effortlessly between Fixed and Relative positioning

As I work on creating a unique scrolling experience, I aim to have elements stop at specific points and animate before returning to normal scroll behavior once the user reaches the final point of the page. Essentially, when div X reaches the middle of the ...

Using JQuery, ensure that the scroll function runs in advance of the ajax call finishing

I am currently working on using jQuery to scroll down to a text box when the click event occurs. However, I have noticed that the scroll event is happening after the AJAX call within the function. $("#execute_btn").click(function(){ $('html, b ...

Generating a unique user ID similar to Zerodha's user ID using Node.js/JavaScript

For a project I'm working on, I need to create random and unique User IDs. I came across Zerodha's user IDs which are easy to remember. In Zerodha user IDs: The first two characters are always letters followed by four numbers. I want to generat ...

What is the best way to generate a search link after a user has chosen their search criteria on a webpage?

In my search.html file, I have set up a form where users can input their search criteria and click the search button to find information within a database of 1000 records. The HTML part is complete, but I am unsure how to create the action link for the for ...

Did I incorrectly associate the function with the button causing it to always be executed?

I am working on a PHP page, where I have some initial content followed by session initialization code: <?php session_start(); ?> The requirement is to display a disconnect button only if the user is logged in, indicated by the presence of $_SESS ...

How can one decrease the size of a React project?

After running npx create-react-app my-app, the download was quick but then it took over an hour for the installation process to complete. Upon checking the size of the newly installed project, I found that the node_modules folder alone was a whopping 4.24 ...

Altering the state ahead of rendering

I am experiencing an issue where the Parent component is passing empty props to the Child component. This may be due to my attempt to set the state of my data within a function instead of in a constructor (for the Parent component). I only want the state o ...

Can you explain the purpose and functionality of this jQuery code snippet?

const elementsInBody = $("div", $("body")).length; This code snippet reminded me of something I saw in the qUnit documentation, and it's unlike anything I've encountered before. ...

"Effortlessly handle adding and removing items with a single button using

I am working on creating a button functionality where clicking it will either add or delete a record from the database. This button serves as a 'favorite' feature. The desired behavior is as follows; Upon clicking the 'fav' button, th ...

Utilize a single CDN or multiple CDNs to access and retrieve files

When I visit a standard webpage, I usually load the following resources from various CDNs: jQuery Angular Bootstrap Icomoon several Angular plugins Would it be more efficient to load all these resources from a single CDN, or is it fine to use multiple ...

The code inside the if statement is somehow executing even when the if statement is not true

Similar Question: Issue with jQuery function running at inappropriate times I've spent several hours trying to figure out why my function isn't working properly. I have a function inside an if ($window.width() < 1000) statement, but it se ...