Stop the timer on a photo carousel when clicking on an image

After creating a photo slider and implementing some w3 CSS to display a photo modal upon clicking an image in the slider, I encountered an issue. When the JavaScript code tries to slide the slider, it disrupts the modal if it is open. Is there a way to pause the JavaScript when the modal is opened?

Here is my PHP code:

function getSlideshow($conn) {
    $sql = "SELECT * FROM status WHERE status_image!='noimage.png' ORDER BY likes DESC LIMIT 8";
    $query = mysqli_query($conn, $sql);
    $i = 0;
    while ($row = $query->fetch_assoc()) {
        if($i % 4 == 0 && $i) echo "</div>";
        if($i % 4 == 0) echo "<div class='inner'>";
        echo "
        <div class='imagebox'>
            <img src='images/".$row['status_image']."' onclick='document.getElementById(\"modal".$row['sid']."\").style.display=\"block\"' class='w3-hover-opacity'>
            </div>
            <div id='modal".$row['sid']."' class='w3-modal' onclick='this.style.display=\"none\"'>
    <span class='w3-closebtn w3-hover-green w3-container w3-padding-16 w3-display-topright'>&times;</span>
    <div class='w3-modal-content w3-animate-zoom'>
      <img src='images/".$row['status_image']."' style='width:100%'>
  </div>
</div>

        ";
        $i++;
    }
    if($i % 4) echo '</div>';
}

And here is the JS/JQuery code:

    $("#slideshow1h > .inner:gt(0)").hide();

setInterval(function() {
  $('#slideshow1h > .inner:first')
    .fadeOut(1500)
    .next()
    .fadeIn(1500)
    .end()
    .appendTo('#slideshow1h');
}, 6000);

Answer №1

When using setInterval, it will return an ID, usually 1, so you have the option to either clearInterval(1) directly or assign the interval function to a variable and use clearInterval(myTimer)

$("#slideshow1h > .inner:gt(0)").hide();

setInterval(function() {
  $('#slideshow1h > .inner:first')
    .fadeOut(1500)
    .next()
    .fadeIn(1500)
    .end()
    .appendTo('#slideshow1h');
}, 6000);

$('img').on('click', function() {
 clearInterval(1);
});

If you want to stop the interval indefinitely, you need to call clearInterval, and then reinitiate the setInterval when needed.

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

Images cannot be uploaded using ajax

I have been troubleshooting an issue with uploading image files using ajax without refreshing the page. However, I am facing a problem where the file does not get moved to the specified folder even after implementing basic PHP code for file upload. if($_S ...

"By selecting the image, you can initiate the submission of the form

I am trying to figure out why clicking on the image in my form is triggering the form submission by default. Can someone please provide guidance on this issue? <form name="test1" action="er" method="post" onsubmit="return validateForm()" <input ty ...

Creating a universal header for all webpages in Angular JS by dynamically adding elements using JavaScript DOM manipulation techniques

I have successfully created a json File containing an array of "learnobjects", each including an id, name, and link. Check out my plnkr example var myMessage = { "learnobjects": [{ "id": "1", "name": "Animation-Basics", "link": "animation_bas ...

Checkbox click triggers a delayed update to the array

In my attempt to develop an array of user permissions that can be managed through a series of checkboxes, I encountered an issue. When I select a checkbox and use console.log() to display the array, it shows all the permissions I have checked. However, upo ...

Attempting to sort through an array by leveraging VueJS and displaying solely the outcomes

Within a JSON file, I have an array of cars containing information such as model, year, brand, image, and description. When the page is loaded, this array populates using a v-for directive. Now, I'm exploring ways to enable users to filter these cars ...

Guide to automatically inserting text into an html form and submitting it without manual intervention

Currently, I am in the process of a project where my main goal is to design an HTML form for submitting replies. One interesting feature I want to include is an option for users who are feeling lazy to simply click on "auto-generate comment", which will ...

What is the best method for testing an Angular service that has dependencies in Jasmine?

My service implementation is structured as follows: angular.module('app').service('MyService' , function (dependency1, dependency2, dependency3 ...) { function funcToTest() { // Do something } } I am wondering how I ca ...

CSS - Choosing between Background Size Contain or Default Size

Is there a solution to my dilemma regarding background images in a div? I need the image to be contained within the div if it's larger (background-size:contain;), but if the image is smaller, I want to keep it as is without stretching or blurring (bac ...

Filtering Gridviews with Javascript or jQuery

My current project involves using an ASP.NET GridView with multiple ListBoxes representing Departments, Categories, Faculties, and more. The data in these ListBoxes and the GridView is dynamically loaded from a MSSQL database in the codebehind. I am in ne ...

Nested asynchronous mapping in Node.js involving multiple HTTP requests

Currently, I am attempting to iterate through an array of URLs and retrieve responses from a specific set of URLs. The goal is for the outer loop to only proceed after all inner requests have been completed, resulting in the desired outcome as shown below: ...

Determine the total count of files in queue with Uploadify prior to initiating the upload process

When I specify auto: false in the uploadify settings, the upload process will only start when the submit button is clicked. Once the onQueueComplete event is triggered, the form will be submitted. However, if no files are selected, the onQueueComplete even ...

Tips for enabling simultaneous input focus on both TextField and Popover components

I am working on a popover component that appears below a textfield component. The goal is to trigger a menu when the user types a specific key, like :, into the textfield. The user can then select an option from this menu to autocomplete the textfield. A ...

Problem with the getJSON function

Here is a question that has been bothering me: I am currently working on a barcode scanner script which retrieves data from a JSON file. The script itself functions properly, except for one issue. After the while loop, I want to display an error alert m ...

Using jQuery to dynamically insert input fields before displaying the Ajax response

As a newly initiated individual to jscript and AJAX, I must admit that this realm seems complex to me. However, I have made significant progress in just 2 days. I am currently working with a GET API that generates the AJAX output progressively using docum ...

Having trouble running Ajax with JavaScript on a Wamp server

Exploring the realm of ajax, I embarked on a journey guided by a YouTube tutorial to construct a basic food search application. The concept was simple - users would input the name of a food item, and if available, its name would be displayed below. On the ...

Error encountered in App.js on line 29: Unable to access the property 'map' as it is undefined

Currently enrolled in the University of Helsinki Full Stack Open course, I am facing a challenging error while working on my React web app. The app retrieves data from the Rest Countries API (https://github.com/apilayer/restcountries) and I am trying to di ...

Is there a way to insert json data into a form input field using jQuery?

I am attempting to insert the JSON result into an input as the value. This is the code I am using: $.ajax({ type:"POST", url: '{% url "url_searchTour"%}', data: data1, success: function(jsonAjaxResult){ console.log(J ...

Passing a string as a parameter in the jQuery animate function tutorial

I am attempting to extract parameters as a string and input them directly into jQuery's animate function like this: Here is my html: <img src="myImage.png" rel="{top:'20px',left:'1000px'},500|{top:'20px',left:'1 ...

Using bufferCount in Rxjs: Retrieving the latest values

Is there a method to access the most recent values emitted while using bufferCount(x), even if the buffer size does not reach x? For example, in the code snippet below, only [0, 1] is printed. I would like the output to also include [2] under certain circ ...

How to delete an item from a dropdown list using Jquery

jQuery(document).ready(function () { $lstAccountType = $('select[id*="account_type"]'); $lstAccountType.change(function () { $(this).remove('option[text="select one"]') }); }); Is there a way to remove the initial option ...