Create a function that will repeatedly call itself at specified intervals, increment a variable, and update the class values of elements with an id matching the current value of the

I'm attempting to create a setup that cycles through different images

                        <div id="img_box" class="shadow" onload="imgCycle(1)";>
                        <img id="1" class='opaque imgbox selected' src="media/imgbox/chem.jpg" />
                        <img id="2" class='imgbox' src="media/imgbox/art.jpg" />
                        <img id="3" class='imgbox' src="media/imgbox/business.jpg" />
                        <img id="4" class='imgbox' src="media/imgbox/chess.jpg" />
                        </div>

by executing a function that removes the styles from all these images

                        function clearActiveImage(){
                        document.getElementById(1).className = "imgbox";
                        document.getElementById(2).className = "imgbox";
                        document.getElementById(3).className = "imgbox";
                        document.getElementById(4).className = "imgbox";
                    }

                        function imgCycle(x) {
                        if ( x == undefined ) { x = 1; }
                        clearActiveImage();
                        document.getElementById(x).className = "opaque imgbox selected";
                        x = x + 1;
                        if ( x >= 4) { x = 1; };
                        setInterval(imgCycle(x), 4000);
                        return;
                    };

then it increments a counter, and calls itself again after 4 seconds with the new counter. If the counter reaches 4, it should go back to 1.

I have implemented some css code that only displays the image with the opaque and selected classes.

#img_box img {
  position:absolute;
  left:0;
  -webkit-transition: opacity 1s ease-in-out;
  -moz-transition: opacity 1s ease-in-out;
  -o-transition: opacity 1s ease-in-out;
  transition: opacity 1s ease-in-out;
  opacity:0;
  -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
  filter: alpha(opacity=0);
}


#img_box img.opaque {
  opacity:1;
  -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";
  filter: alpha(opacity=1);
}

The page loads without any issues, but I'm struggling to make this feature work as intended.

Answer №1

Here is the solution you've been searching for:

<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<style type="text/css">
#img_box img {
    position: absolute;
}
</style>

<div id="img_box">
    <img src="http://photo.yourmlssearch.com/11/1_a/4582564-1.jpg" />
    <img src="http://photo.yourmlssearch.com/11/2_a/4582564-2.jpg" />
    <img src="http://photo.yourmlssearch.com/11/3_a/4582564-3.jpg" />
    <img src="http://photo.yourmlssearch.com/11/4_a/4582564-4.jpg" />
</div> 

<script type="text/javascript">
$('#img_box').append('<img src="'+$($('#img_box img')[0]).attr('src')+'">');

$('#img_box img').each(function(index,item){
    $(this).css('z-index',$('#img_box img').length - index);
});

setInterval(function(){
    var visibleImages = $('#img_box img:visible');

    if(visibleImages.length == 1) {
        visibleImages.css('z-index',$('#img_box img').length + 1);

        $('#img_box img').each(function(index,item){
            $(this).css('z-index',$('#img_box img').length - index).show();
        });
    }
$($('#img_box img:visible')[0]).fadeOut(4000,function(){

});
},10);
</script>

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

Finding the value of an input without having to submit it first and searching for it within a datalist

> Here is an example of HTML code <label>Person</label> <input name="PersonID" type="text" id="PersonID"> <label>Car Plate Number</label> <input name="PersonsCarPlateNumber" list="PersonsCarPlateNumbe ...

Achieve the central element while scrolling on the window

What am I doing wrong? I've been attempting to target the #second element on scroll Here is an example with console.log CODEPEN EXAMPLE $(window).scroll(function(){ var section = $("#second").offset().left, scrollXpos = $( ...

Unable to invoke any fineUploader functions within a callback function

My autoUpload is currently set to false because I prefer uploading the images manually to my backend. To achieve this, I need the file object first. In the onSubmitted event callbacks, I am attempting to pass the image's ID to the getFile method to re ...

The state value in React useContext remains unchanged when navigating between pages

Currently, I am delving into the useContext hook and experimenting with a shopping cart exercise in Next.js with app router. This exercise involves managing the cart's value globally. However, I encountered an issue when trying to pass the updated ca ...

Is Nuxt's FingerprintJS Module the Ultimate Server and Client Solution?

I am currently using fingerprintJS in my NuxtJS+Firebase project VuexStore. When I call the function on the client side, I can retrieve the Visitor ID. However, I am encountering issues when trying to use it on the server side, such as in nuxtServerInit. ...

What causes inability for JavaScript to access a property?

My current coding project involves the usage of typescript decorators in the following way: function logParameter(target: any, key : string, index : number) { var metadataKey = `__log_${key}_parameters`; console.log(target); console.log(metadataKey ...

Exploring the power of Jade and Angular through implementing a for loop within a table structure

I'm brand new to using Jade and Angular, and I could really use a hint from someone more experienced. ... - for (var i = 0; i < p.length; i++) tr td= i + 1 td= price(value='p[i].somedbstuff') ... I want the la ...

Guide on extracting data from a JavaScript table using Python

Looking to extract information from a table on this page: . There are a total of 18 pages, but the url remains constant for each page. My usual method involves using BeautifulSoup to scrape data from HTML pages. However, in this case, the required data is ...

What is preventing the question div and buttons from expanding according to their content?

After experimenting with setting the height of the question div to auto, I found that it would stretch to fit its content. However, I am looking for a solution without overflow: auto or scroll. Is there a limit to how responsive it can be once a certain ...

What is the best way to draw a rectangle outline in Vue.js without the need for any additional packages?

I have been attempting to craft a rectangle outline using vueJS, but so far I have not had much success. I am hoping to achieve this using only CSS, but despite my efforts, I have not been able to find a solution. My goal is to create something similar to ...

Preventing jQuery from removing child elements while inserting data through ajax

When I try to insert data into an HTML structure using the code below, only one of the elements displays at a time. It seems like when I use Ajax to insert data, the child elements are being removed. How can I prevent this without having to change the stru ...

Import an array of dynamic modules with Webpack that are known during compilation

For my project, I have the requirement to import specific modules whose actual paths are only known during compile time. Imagine having components/A.js, components/B.js, and components/C.js. In my App.js, I need to include a subset of these modules that w ...

What is the best way to connect or link to a HTML table row <tr>

Is there a way to trigger an alert when the user double clicks on the whole row? ...

What is the method to utilize global mixin methods within a TypeScript Vue component?

I am currently developing a Vue application using TypeScript. I have created a mixin (which can be found in global.mixin.js) and registered it using Vue.mixin() (as shown in main.ts). Content of global.mixin.js: import { mathHttp, engHttp } from '@/ ...

The password encryption method with "bcrypt" gives an undefined result

import bcrypt from 'bcrypt'; export default class Hash { static hashPassword (password: any): string { let hashedPassword: string; bcrypt.hash(password, 10, function(err, hash) { if (err) console.log(err); else { ha ...

Managing form submissions using Material UI and Next.js

Can someone provide insights on using Material UI with Next Js? I am experimenting with a Login template from Material UI, but I am facing an issue where query params are added to the URL upon Submit. For example: localhost:3000/auth/login changes to: ...

Default parameter in Node.js is set when the callback function is the last parameter

Here's a simplified version of the function I'm working with: doSmthg (name, age, callback) { callback(name, age); } I want to set a default value for age if it's not provided. In ES6, I could do doSmthg(name, callback, age=42) {...}, b ...

Comparison between on() delegation and delegate()

When using <strong>$(document).on('click', '#target')</strong> versus <strong>$('body').delegate('click', '#target');</strong> It seems like both options achieve the desired outcome ...

CSS: How to target a specific element using its ID with nth-child selector?

Here is the HTML code that I am working with: <dl id="id"> <dt>test</dt> <dd>whatever</dd> <dt>test1</dt> <dd>whatever2</dd> .... </dl> I am trying to select the third dd ele ...

Tips for creating a captivating full-screen parallax section on your website

Is there a way to make the first section of a parallax site full screen? I've been scouring the internet for a solution to this problem, but I'm not having any luck. Almost every parallax site I come across has their first section full screen, a ...