Navigate between pictures using hover in jQuery

I am working on creating a feature where images cycle through individually every 2 seconds, but switch to the right image when its associated link is hovered. So far, I have managed to make the images show up on hover, but I am struggling with getting them to cycle automatically.

$("#one").on({
mouseover: function () {
    timer = setTimeout(function () {
        $("#first").removeClass('hidden').css('opacity', '1');
    }, 300);
},
mouseout: function () {
    clearTimeout(timer);
    $("#first").css({
        'opacity': '0'
    }).addClass('hidden');
}
});

https://jsfiddle.net/enwed7b9/1/

Answer №1

You may have encountered some broken image links in your HTML code, but fear not! This solution should resolve the issue: https://jsfiddle.net/pengyanb/st47yxqb/6/

var imageIndex = 0;
var periodicTimer;
setPeriodicTimer();

function setPeriodicTimer()
{
    periodicTimer = setTimeout(function(){
        $('img').addClass('hidden').css('opacity', '0');
        console.log('imageIndex: '+imageIndex);
switch(imageIndex)
        {
            case 0:
                $('#first').removeClass('hidden').css('opacity', '1');
                break;
           case 1:
                $('#second').removeClass('hidden').css('opacity', '1');
                break;
           case 2:
                $('#third').removeClass('hidden').css('opacity', '1');
                break;       
           case 3:
                $('#fourth').removeClass('hidden').css('opacity', '1');
                break;
   
           case 4:
                $('#fifth').removeClass('hidden').css('opacity', '1');
                break;
           case 5:
                $('#sixth').removeClass('hidden').css('opacity', '1');
                break;
           case 6:
                $('#seventh').removeClass('hidden').css('opacity', '1');
                break;
        }
        imageIndex++;
        if(imageIndex > 6)
            imageIndex = 0;
        setPeriodicTimer();
}, 2000);
}

$("#one").on({
    mouseover: function () {
        clearTimeout(periodicTimer);
        imageIndex = 0;
        $('img').addClass('hidden').css('opacity', '0');
        timer = setTimeout(function () {
            $("#first").removeClass('hidden').css('opacity', '1');
        }, 300);
    },
    mouseout: function () {
        setPeriodicTimer();
        clearTimeout(timer);
        $("#first").css({
            'opacity': '0'
        }).addClass('hidden');
    }
});
<!-- The rest of the JavaScript code is similar to the above snippet -->
.box {
    position: relative;
    display: inline-block;
    height: 15px;
    line-height: 15px;
    text-align: center;
    transition: .3s;
    cursor: pointer;
    margin-bottom: 4px;
    margin-right: 3px;
    padding-bottom: 7px
}

.image {
    width: 100%;
    z-index: -1
}
.image img {
    margin: auto;
    position: absolute;
    top: 0;
    left: 10%;
    bottom: 0;
    right: 0;
    width: 55%;
    transition: ease-out .4s;
    z-index: -1
}
.hidden {
   
    opacity: 1
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="project-link-2">
    <!-- Your HTML content with project links and images here -->
    
    </ul>
        
        
<div class="image">
    <img alt="" class="hidden" id="first" src="http://consequenceofsound.files.wordpress.com/2013/06/datside-ram.jpg">
</div>
<!-- Rest of the image elements -->

Answer №2

This code snippet enables cycling through images every 3 seconds, pausing the cycle and displaying the hovered image when the user hovers over a link.

var autoCycle = true;
var i = 1;
var images = [
    $('#first'),
    $('#second'),
    $('#third'),
    $('#fourth'),
    $('#fifth'),
    $('#sixth'),
    $('#seventh')
];

images[0].removeClass('hidden').css('opacity', '1');

setInterval(function() {
    if(autoCycle) {
        images.forEach(function(img) {
            img.css({ 'opacity': '0' }).addClass('hidden');
        });

        var currImage = images[(i - 1) % images.length];
        var newImage = images[i % images.length];

        currImage.css({ 'opacity': '0' }).addClass('hidden');
        newImage.removeClass('hidden').css('opacity', '1');

        i++;
    }
}, 200);

To control the auto-cycling behavior based on user hover actions, update the calls to on() as follows:

$("#one").on({
    mouseover: function () {
        autoCycle = false;
        timer = setTimeout(function () {
            $("#first").removeClass('hidden').css('opacity', '1');
        }, 300);
    },
    mouseout: function () {
        autoCycle = true;
        clearTimeout(timer);
        $("#first").css({
            'opacity': '0'
        }).addClass('hidden');
    }
});

Answer №3

This content should aim for maximum generality,

Efforts should be made to minimize redundant code. A universal functionality can be established with the incorporation of image links in the subsequent manner:

HTML: (unique data-id attributes used as image links)

<ul class="project-link-2">
    <li class="box" data-id="first"> <a class="project-link" href="#modal1"><span>Modurra Shelving</span>   </a>    
    </li>
    <br>
    <li class="box" data-id="second"> <a class="project-link" href="#modal2"><span>Kami Bicycle Helmet</span> </a>  
    </li>
    <br>
    <li class="box" data-id="third"> <a class="project-link" href="#modal3"><span>Revamping Language Learning</span> </a>   
    </li>
    <br>
    <li class="box" data-id="fourth"> <a class="project-link" href="#modal4"><span>Sports Innovation Challenge</span> </a>  
    </li>
    <br>
    <li class="box" data-id="fifth"> <a class="project-link" href="#modal5"><span>Lights Out</span></a> 
    </li>
    <br>
    <li class="box" data-id="sixth"> <a class="project-link" href="#modal6"><span>Maru Personal Speaker Design</span> </a>  
    </li>
    <br>
    <li class="box" data-id="seventh"> <a class="project-link" href="#modal7"><span>A Few Casual Projects</span> </a>   
    </li>
</ul>

<!-- Images -->
<div class="image">
    <img alt="" class="hidden" id="first" src="http://consequenceofsound.files.wordpress.com/2013/06/datside-ram.jpg">
</div>
<!-- Lights Out -->
<div class="image">
    <img alt="" class="hidden" id="second" src="http://tctechcrunch2011.files...">

JS: (condensed and optimized code)

var position = 0 / 1; // Ensure integer value
var myImgArr = $(".image img");
var count = myImgArr.length;
var timer;

$(function () {
    $(myImgArr[0]).removeClass('hidden'); // Show first image on page load
    timer = setInterval(setMySlider, 2000); // Initiate slider function
});

$(".project-link-2 li").mouseenter(function () {
    clearInterval(timer);
    myImgArr.addClass('hidden');
    myID = '#' + $(this).attr('data-id');
    $(myID).removeClass('hidden');
}).mouseleave(function () {
    myID = '#' + $(this).attr('data-id');
    $(myID).addClass('hidden');
    $(myImgArr[mod]).removeClass('hidden');
    timer = setInterval(setMySlider, 2000);
});

function setMySlider() {
    mod = ((position % count) / 1);
    $(myImgArr[mod]).addClass('hidden');
    position++;
    mod = ((position % count) / 1)
    $(myImgArr[mod]).removeClass('hidden');
}

Access Fiddle here

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

Bootswatch is causing the Bootstrap tooltip feature to malfunction

Could someone help me figure out why my tooltip isn't functioning properly? The HTML Code in Question: <div class="form-check"> <label class="form-check-label" > <input type="radio" class="form-check-input" name= ...

What's the best way to ensure uniform spacing between the list items in this slider?

When using appendTo, I've noticed that the spacing between items disappears. I've tried adjusting the padding-bottom and left properties with no success. Does anyone have a suggestion for how to fix this issue? I'm at a standstill. $(&a ...

Retrieving data and selecting tables using jQuery

Currently, I have an HTML table displaying various available times for scheduling purposes. My goal is to allow users to click on a specific time slot and retrieve both the column header (staff person's name) and the value of that cell (the time). Aft ...

Discover the method to calculate the combined file size of multiple uploads with jquery

One of the challenges I'm facing is ensuring that users can only upload multiple files if the total size does not exceed 3GB. Is there a way I can enforce this limit? Below is the current code snippet I am using: var fileCount = 0; var showFileCo ...

I'm puzzled as to why my fixed element is gravitating towards the right side of the entire screen instead of aligning with the right side of its parent element

I have inserted a code snippet that highlights my issue. I am attempting to ensure that the .navigation element remains fixed at the top of the colored divs, however, when using 'right: 0;', the .navigation element seems to shift to the right sid ...

Send information from a web page's elements to PHP with the help of AJAX

My goal is to integrate AJAX, HTML, and PHP to create a seamless user experience. I am currently facing difficulty in passing variables to the PHP form. The method I've employed seems a bit complex, especially since this is my first attempt at using A ...

Can you explain the functionality of isolate scope in angularjs?

I'm having trouble grasping the concept of scope : {}. Here's a snippet of code I've been working on. Why does it always display "strength" in the console instead of the actual array value? // Code goes here var app = angular.module("super ...

The ReactJS Material Table Tree mode experiences delays when new row data is introduced

My Reactjs app utilizes the material-table widget within a component: render() { return ( <div> <Row> <MaterialTable title="Mon équipement" style={{ width: "100%", margin: "0%" }} ...

Having trouble with the clear button for text input in Javascript when using Bootstrap and adding custom CSS. Any suggestions on how to fix

My code was working perfectly until I decided to add some CSS to it. You can view the code snippet by clicking on this link (I couldn't include it here due to issues with the code editor): View Gist code snippet here The code is based on Bootstrap. ...

Tips for limiting users to inputting only alphanumeric characters and excluding special characters in an input field using Angular 8

How can I prevent users from inputting special characters in an input field and only allow alphanumeric values? The code that I have implemented so far does not seem to be working as intended. When a user enters a special character, it still shows up in th ...

Would like to conceal an element only if it is currently visible

Currently in the process of developing a website, I have successfully implemented a dropdown menu that is triggered when clicking on an "About Me" link. This reveals additional links such as biography and interests. The issue I am facing now is regarding t ...

Learn the process of transforming a filter into a directive in AngularJS

Here is a question I asked previously, where I was looking to remove negative numbers from an input field: <input type = "text" ng-model="number"></input> In that previous question, Paritosh provided me with a helpful solution, but now I am i ...

Utilize AngularJS to integrate a service into the router functionality

What is the best way to inject a service into my router so that its JSON result will be accessible throughout the entire application? Router: export default ['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterP ...

Using JavaScript code to sift through and eliminate irrelevant data

Recently, I started learning about angular js and came across a link from which I need to extract a list of names and ids. I successfully retrieved the list in json format, but now I need to filter out unwanted items. The criteria for filtering is based ...

Genvalidator: Validate forms by checking for checkbox selection

Currently, I am utilizing genvalidator to conduct tests on input fields within a form. One issue I am encountering is the inability to determine if a checkbox has been checked. Below are the settings for all fields: frmvalidator.addValidation("name","req ...

What is the best way to determine if a radio button has been chosen, and proceed to the next radio button to display varied information?

The goal is to display the <div class="resp"> below each radio button when it is selected, with different content in each <div class="resp">. The previously selected <div class="resp"> should be hidden when a new radio button is chosen. O ...

What causes TypeScript generics to infer varying types when an array member is enveloped?

I'm having trouble finding an answer to this potentially duplicate question, so please redirect me if it has already been addressed. My experience with generics in TypeScript has shown me that the inferred types can vary based on whether a generic is ...

Having trouble installing @angular/cli 4 on Debian?

I'm having trouble installing @angular/cli on my Debian box. I already have the latest versions of Node.js and npm installed. Interestingly, Angular4 works perfectly fine on my Windows machine where I use it daily. However, when I try to get it runnin ...

Achieving a sleek line effect with a gradient border

Is there a way to make the gradient border transition between two colors look like a straight line? Additionally, is it possible to have the line start in the bottom left corner instead of the middle of the right side of the button? The current CSS code I ...

Variations in jQuery's append method when dealing with a string, a reference to a jQuery object

Here are multiple ways to add a div element to the body of an HTML document. But what distinctions exist between them and in what scenarios should each be utilized for optimal performance? var newDiv = '<div id="divid"></div>'; $(&ap ...