Is there a way for me to modify this carousel so that it only stops when a user hovers over one of the boxes?

I am currently working to modify some existing code to fit my website concept. One aspect I am struggling with is how to make the 'pause' function activate only when a user hovers over one of the li items, preventing the carousel from looping endlessly.

Do you have any suggestions on how this can be accomplished? I have tried different approaches like:

if ($('#element:hover').length != 0) {
    pause();
}

However, these attempts do not align with the current code structure. Could someone provide me with guidance on this issue? Thank you.

https://jsfiddle.net/lovromar/Z4VpZ/

HTML

<div id="carousel-container">
    <div id="carousel-inner">
        <ul id="carousel-ul">
            <li>1</li>
            <li>2</li>
            <li>3</li>
            <li>4</li>
            <li>5</li>
            <li>6</li>
            <li>7</li>
            <li>8</li>
            <li>9</li>
            <li>10</li>                  
        </ul>
    </div>
</div>

CSS

#carousel-container {
    width:680px;
    margin:2em auto;
    position:relative;
    border:1px solid #ccc;
    overflow:hidden;
    height:250px;
}

#carousel-inner{
    width:680px;
    float:left;
    position:relative;
    overflow:hidden;
}

#carousel-ul {
    position:relative;
    left:-160px;
    list-style-type:none;
    margin:0px;
    padding:0px;
    width:9999px;
    padding-bottom:50px;
}

#carousel-ul li{
    float:left;                                    
    width:150px;  
    padding:0px;
    height:186px;
    margin:50px 15px 0 15px;
    position:relative;
    background:#c0c0c0;
    line-height:186px;
    font-size:2em;
    text-align:center;
}

JS

var Carousel = new
function() {

    var wrapper = document.getElementById('carousel-container'),
        timer = null;

    var start = function() {

        doCarousel();
    };



    var sliding = function() {



        var item_width = $('#carousel-ul li').outerWidth()+10;


        var left_indent = parseInt($('#carousel-ul').css('left'))-item_width;


        $('#carousel-ul:not(:animated)').animate({
            'left':left_indent
        },2000,'linear',function() {


            $('#carousel-ul li:last').after($('#carousel-ul li:first'));


            $('#carousel-ul').css({
                'left':'-160px'
            });
        });




    };

    var doCarousel = function() {

        timer = setInterval(sliding,2000);


    };

    var pause = function() {

        clearInterval(timer);
        timer = null;


    };

    var resume = function() {
    doCarousel();


};

this.init = function(){

    start();


};


}();

$(function(){

Carousel.init();

});

Answer №1

I successfully implemented the solution.

The modification I made was in changing how the object is declared, and now it functions as intended:

var Carousel = {
    timer :null,
    wrapper: null,
    init : function()
    {
        var self = this;
        this.timer = setInterval(function(){self.sliding();}, 2000);
    }, 
    sliding : function() {
        var item_width = $('#carousel-ul li').outerWidth() + 10;
        var left_indent = parseInt($('#carousel-ul').css('left')) - item_width;
        $('#carousel-ul:not(:animated)').animate({
            'left': left_indent
        }, 2000, 'linear', function() {

            $('#carousel-ul li:last').after($('#carousel-ul li:first');

            $('#carousel-ul').css({
                'left': '-160px'
            });
        })},
        pause : function() {
            clearInterval(this.timer);

            this.timer = null;

        },
        resume : function() {
            this.init();
        },

};

$(function() {
    alert("init");
    Carousel.init();
    $('#carousel-ul li').mouseover(function(){ 
        //clearInterval(timer);
        //timer = null;
        //pause();
        Carousel.pause();
    });
 $('#carousel-ul li').mouseout(function(){ 

    //clearInterval(timer);
    //timer = null;
    //pause();
     Carousel.resume();
});

});

Here is the Jsfiddle link for reference: https://jsfiddle.net/Z4VpZ/4/

In general, I prefer not to use JavaScript function for class declaration, opting instead for js object {}, or leveraging the ECMASCRIPT 6 class statement.

Answer №2

Have you attempted a similar approach?

$("#carousel-ul li").mouseenter(function(){ Carousel.stop();});

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

The drop-down menu is misaligned from its designated position underneath the title

Trying to incorporate a dropdown menu into my website, I am structuring the HTML as follows: <ul class="topnav"> <li> SECTION TITLE <ul class="subnav"> <li>One</li> <li>Two</li> ...

Please execute the npm install command to install the readline-sync package in order to fix the error in node:internal/modules/c

Having trouble installing npm readline as it keeps showing errors, even after trying different solutions. Tried deleting folders and uninstalling nodejs but the issue persists. Need help fixing this problem. ...

Challenges encountered while constructing a flexbox layout

I have a flexbox design that I am trying to create with the specific layout shown in the image: https://i.sstatic.net/Sy20K.jpg My HTML code is as follows (and I do not want to make any changes to it): <div class="wrapper"> <div class="page-h ...

Modifying a css class via javascript

Is it possible to set an element's height using CSS to match the window inner height without directly modifying its style with JavaScript? Can this be achieved by changing a CSS class with JavaScript? One attempted solution involved: document.getEle ...

Use jQuery to parse the JSON below and then showcase the information in an HTML table

Can anyone assist me with parsing the following JSON using jQuery and presenting it in an HTML table? I want to showcase the values of "key" and "doc_count" in an HTML table. Your help would be greatly appreciated. Please find the JSON data below: { ...

Tips for maximizing website performance on touch-enabled devices

When using a touch device such as an iPhone, iPad, or Android device, it can be challenging to accurately tap on small buttons with your finger. So far, there is no universal method in CSS media queries to detect touch devices. As a workaround, I check if ...

Fixed-top navbar in Bootstrap obscuring webpage contents

I have tried various solutions to the issue at hand, but nothing seems to be working. I applied padding-top to the container of my main content, but when I add the following CSS: @media (max-width: 768px) { body{ padding: 0; } } it overrides the padd ...

Exploring ways to access elements within shadow-root (open) in Angular using SVG.js

I'm currently tackling a project involving Angular Elements. Within this specialized component, my goal is to incorporate SVG.js 3+. However, due to the necessity of utilizing ViewEncapsulation.ShadowDom in my component, I am encountering challenges w ...

Clear the cache in Angular to remove the page

Within my current project, I am utilizing angular's $routeProvider to dynamically load pages into an ng-view section. The loaded pages are displaying correctly in the ng-view and are being cached for quick access without needing to make a new server r ...

Most effective method for displaying modals in React

I've recently started learning ReactJS and I'm exploring the use of modal windows. However, I'm uncertain about the most appropriate approach to take. Currently, I am implementing modals using callbacks. Reactstrap Modal Dialog Component: ...

Angular material is experiencing an issue where content is being cut off or

I am currently working on a project using AngularJS for a web application. I have encountered an issue where some of the content in the md-content element is being clipped. For instance, the body tag has the style: overflow: hidden, and the child md-conte ...

A guide on dragging a box using JavaScript

I recently came across a box similar to the one in the image below: <div id="HelpDoc"> <div id="HelpHeader">Here goes the header</div> <div id="HelpContent">Here goes the content</div> </div> I am looking for a ...

"The jQuery AJAX function is displaying an error message indicating that the resource was

Does anyone have experience using jQuery AJAX to send data from the client side to the server? I thought it would be straightforward, but I keep getting a "not found" error. Here's the AJAX code I'm using: <script type="text/javascript"> ...

What is the best method for deleting an uploaded image from a box?

My code is quite lengthy, so I'll just showcase the JavaScript portion here. Here is a snippet of my JavaScript code: <script type="text/javascript"> let current = 0; for(let i = 0; i < 5; i++) { $('#thumbnail-view- ...

Having trouble retrieving the ng-model value from input in the controller

I am new to Angularjs and I am working with a datepicker in Ionic. After selecting a date, the input field is correctly getting the value of the selected date. However, I am facing an issue when trying to access this value in the Controller using $scope. ...

My div won't stay fixed in the layout no matter what I try

Being fairly new to css, divs, and everything in between, I decided to create a simple layout for my band without unnecessary links like bio or merch store. Instead, I wanted separate spaces for our video, music player, and a Facebook window. I successful ...

tag of data in jquery

Here is how my setup looks: <div onclick="EditCalendarEvent('@_schedulerEvent.SchedulerID','@_schedulerEvent.SchedulerItemID', event)" class="ScheduleEvent_Draggable ScheduleEvent" data-schedulerID="@_schedul ...

Tips for concealing items on a website within a WebView

Is it possible to hide the header element with the search bar and logo when loading this page on a Webview? I'm not familiar with JavaScript, so is there a way to achieve this? The section I am looking to conceal ...

Issue: ENOENT error occurred during execution on Docker Container due to missing file or directory '/root/.aws/credentials'

click here for image description While the app runs normally locally, attempting to run it in a Docker container results in an error displayed on the screen. This is my Docker file: FROM node:14.0.0 WORKDIR /app ARG DATABASE_URL ARG AWS_REGION ARG CLIENT_ ...

What is the best way to conceal an element in a loop using React?

I'm facing an issue with this short React code where I'm trying to hide the header that corresponds to a button when that button is clicked. I want only the specific header and button to disappear within the loop. How can I achieve this? For exa ...