In order to enable automatic playback of background images

Having created a slider with hover functionality on icons to change background images, I now seek to add an autoplay feature to the slider. The slider was implemented in a WordPress project using Elementor and involved custom Slider creation through JavaScript DOM manipulation.

How can I achieve simultaneous autoplay of background images along with changing them upon hovering over the icon?

Here is the JavaScript code responsible for changing the background image when an icon is hovered:

<script>

const backgroundChange = document.querySelector('#hero-section');

const icons = document.querySelectorAll('.icon');

icons.forEach(icon => {
    icon.addEventListener('mouseover', function(){
        const imageUrl = this.getAttribute('data-image');
        backgroundChange.style.backgroundImage = `url(${imageUrl})`;
    });
});

backgroundChange.style.autoPlay = 'true';

</script>

<style>
#hero-section{
transition: background 0.4s linear;
}
</style>

Answer №1

To create a solution, you can implement an autoplay image links array and use the setTimeout() function to continuously change the background image of an element from that array. Whenever someone hovers over the background, you can set a custom background image and disable the autoplay mode by setting a boolean value to false. Here is an example :

<H2 style="color:cyan">Hover mouse to switch-off autoplay and change background</H2>
<script>
var images = ['https://upload.wikimedia.org/wikipedia/commons/3/34/Midland_4-2-2_No._673_Rainhill_1980_%E2%80%93_edited.jpg',
'https://upload.wikimedia.org/wikipedia/commons/thumb/a/a9/ArcodelaMacarena.jpg/800px-ArcodelaMacarena.jpg'
];
var ix = 0;
var autoplay = true;

function loop(pause=2000) {
      setTimeout(function () {
          if (autoplay) {
            document.body.style.backgroundImage = `url('${images[ix]}')`;
            ix = (ix+1)%images.length;
          }
          loop();
      }, pause);
}

document.addEventListener("mouseenter", function( event ) {
  autoplay = false;
  document.body.style.backgroundImage = `url('https://upload.wikimedia.org/wikipedia/commons/thumb/f/f1/Witton_Lakes_-_Lower_%28448543147%29.jpg/1024px-Witton_Lakes_-_Lower_%28448543147%29.jpg')`;
}, false);

document.addEventListener("mouseleave", function( event ) {
  autoplay = true;
}, false);

loop(0);

</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

React JS - State values are not persisting and rendering properly upon clicking

Recently, I followed a step-by-step tutorial on creating a todo list using functional components. However, I encountered an issue when attempting to delete or mark items as complete in the list. In both the deleteHandler and completeHandler functions, I tr ...

Express Promises Linked Together: Lack of Data in Last Stage

When handling put requests for my restful API, I utilize the findOneAndUpdate method of Mongoose. The password is left to the second step where the 'save' pre hook of Mongoose is used to hash the password. router.put("/:id", function(req, res, n ...

Achieve a full page layout with content and attach the footer to the bottom using flexbox in Tailwindcss and Nextjs

How can I use flex-grow to make the body section fill the screen and keep the nav fixed at the bottom? I'm having trouble figuring out which elements to apply these properties to. Can anyone provide guidance on which element should have these styles? ...

Issues with logging functionality in my React Native application

I am currently facing an issue with my React Native app running on the Android Studio emulator. The logging does not appear in my terminal or in the active remote debugger in Chrome when debugging is enabled. When I attempt to log a simple text in one of m ...

What causes AJAX to disrupt plugins?

I am facing a challenge with my webpage that utilizes AJAX calls to load content dynamically. Unfortunately, some plugins are encountering issues when loaded asynchronously through AJAX. I have attempted to reload the JavaScript files associated with the ...

Webpack 4.1.1 -> The configuration.module contains a property 'loaders' that is unrecognized

After updating my webpack to version 4.1.1, I encountered an error when trying to run it: The configuration object is invalid. Webpack has been initialized with a configuration that does not match the API schema. - The 'loaders' property in ...

Getting field values from Firestore in a React application

Within my firestore document, I have three fields that store boolean values critical for subsequent processing. To access these boolean values in my program, I need to figure out how to read the fields of a document. This process should be straightforward, ...

Keeping the header fixed on a sticky div (tocbot)

While working on my website, I decided to implement a Table of Contents section using tocbot. However, I encountered an issue where the Title I added above the table doesn't stay fixed when scrolling. https://i.stack.imgur.com/vCm1K.gif Here's ...

Javascript: What is the best way to narrow down search results using multiple values, regardless of the sequence in which they are entered?

React: How can I improve search result filtering to accommodate multiple values (irrespective of word order)? Example: I want to search for the title of a document using variations like "phone repair process," "repair phone process," or "process phone repa ...

What steps can I take to eliminate the initial delay when it is first invoked?

My function is being called every 10 minutes like this: var interval = self.setInterval(my_func, 600000); function my_func(){ $.ajax({ url: 'xxxxxxxx', success: function(response) { var data= JSON.parse(response); dis ...

Using blending modes with gradient colors in an SVG design

I'm struggling to get my logo to change colors upon scrolling into a button with similar gradient colors, but I just can't seem to make it work. Can anyone lend me a hand? Thank you! Take a look at my Logo. I've attempted to add some styles ...

evt.target consistently returns the initial input within the list of inputs

My React file uploader allows users to attach multiple file attachments. Each time a user clicks on an input, I retrieve the data-index to identify the input position. renderFileUploader() { let file_attachment = this.state.file_attachment.map(fun ...

What would be the ideal alternative if the Google Ajax API is unavailable, given that Google does not allow for local installation?

On my website, I include the following script: ... <script type="text/javascript" src="https://www.google.com/jsapi"></script> ... This particular script is from Google and is used to dynamically load other resources, such as the Google Chart ...

What is the procedure for utilizing the comparator to arrange items according to various attributes?

I am trying to find a way to arrange my models in a collection based on their required flag and then alphabetically by their value. This is what my current code looks like: var myModel = Backbone.Model.extend({ defaults: { required: true, ...

Sequelize makes it easy to input records into various tables simultaneously

Embarking on my first experience with Sequelize and MySQL, I am seeking guidance on inserting data into two tables with a foreign key relationship. Let's delve into the structure of the entities - bookingDescription and bookingSummary. //bookingSumma ...

Is there a way to retrieve the ngModel reference of a child element within a directive's

I am currently utilizing bootstrap-colorpicker along with an angular directive in my project. Within my form, there is a colorpicker that I want to monitor for any changes. However, since the colorpicker jQuery plugin updates the value of the colorpicker, ...

Steps for obtaining the current state array post re-ordering column in Angular datatables

I am facing an interesting scenario where I can successfully retrieve the current state of an array of columns using pure JS + jQuery, but unfortunately, the same approach does not seem to work in Angular 12! Despite going through the documentation for Ang ...

Passing props from a parent component to a nested child component in Vue 3

My goal is to achieve the functionality described in the title. Suppose I have the following structure: parent -> child -> secondChild Currently, there is a variable called isActive in the parent component. Below is how it can be implemented: paren ...

How can you sort an array based on a shared object property using Angular.js?

I've been grappling with this issue for a while now. My app receives data about individuals in JSON format: "people": [ { "name": "Ivan", "city": "Moscow", "country": "Russia" }, { "name": "John", ...

Guide on sending data to MongoDB using Postman

I am currently facing an issue while trying to send data to the MongoDB database using Postman. Despite everything seeming fine, I keep encountering errors. https://i.stack.imgur.com/Gcf5Q.jpg https://i.stack.imgur.com/ntjwu.jpg https://i.stack.imgur.co ...