Shuffle elements on a page with random CSS class flips using JavaScript

I've implemented a feature on my page where squares can be clicked to flip over like a card, revealing their back side.

Take a look at the interactive demonstration on JS Fiddle: http://jsfiddle.net/d1botfu2/

While this works well, I'd also like to have squares automatically flip over every few seconds, similar to a screensaver. After flipping over, they should return to their original position and another random square should undergo the same animation as the click event.

My attempt at using a toggle caused the square to turn white instead of flipping as intended.

$(document).ready(function () {

function change() {
    randomElements = jQuery("div.flipper").get().sort(function(){
        return Math.round(Math.random())-0.5
    }).slice(0,1)
    $(randomElements).toggle('active');
    console.log("Change");
}

setInterval(function () {
    change();
}, 1000);

});

Answer №1

I have reviewed your code and implemented some necessary fixes. I hope this solution meets your requirements.

$(document).ready(function () {

function change() { debugger;
    randomElements = jQuery("div.flip-container").get().sort(function(){
        return Math.round(Math.random())-0.5
    }).slice(0,1)

    $(randomElements).toggleClass('active');
    console.log("Change");
}

setInterval(function () {
    change();
}, 1000);

});

http://jsfiddle.net/d1botfu2/4/

Answer №2

Check out these references for more information: https://api.jquery.com/eq-selector/

and also visit this link: http://www.w3schools.com/jsref/jsref_random.asp

By using a random number, you have the ability to select a random element from a specified class type.

Here's an untested code example:

$( ".div.flipper:eq(' + Math.floor(Math.random() * 10) + ')" ).trigger('click')

This snippet above is designed to pick a random card within the range of 1 to 10 (more specifically, between 0 and 9) and trigger its click-event.

window.setInterval(function(){
    $( ".div.flipper:eq(' + Math.floor(Math.random() * 10) + ')" ).trigger('click')
    flipTimer ;
}, 1000);

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

`Integrate Passport Azure AD authentication into your GraphQL Server's Context`

Seeking assistance from experienced individuals to tackle some async JavaScript issues. I am trying to secure a GraphQL server using the Passport library and the passport-azure-ad strategy. The validation of incoming Access Tokens seems to be working fine ...

eliminate unnecessary spacing in Twitter's Bootstrap

I am trying to eliminate the extra space between the top and bottom images. Here is my code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>home</title> <link rel="stylesheet" ...

Looking to locate an array within a schema using its unique identifier

const FormFieldsSchema = new Schema({ formName: { type: String, required: true }, fields: [ { fieldLabel: { type: String, required: true }, inputData: [{ type: mongoose.Schema.ObjectId, re ...

Is it possible to move the login button to the right side of the screen?

I'm attempting to move the Login menu all the way to the right on the navigation bar. Currently, all the menu items are aligned to the left and I need to align the Login menu to the right. However, I'm unsure of where to begin. The navigation me ...

Insert JavaScript into this HTML document

I am looking to integrate the "TimeCircles JavaScript library into my project, but I am facing some challenges in doing it correctly. I plan to include the necessary files at the following location: /js/count-down/timecircles.css and /js/count-down/timecir ...

Transfer the chosen item from one select box to another select box while ensuring there are no duplicates

Currently, I have two select boxes and my goal is to transfer options from one select box to another using a button. Here is the code snippet: PHP <table> <tr> <td> <select size="5" id="suppliedMovies" name="supp ...

Automating Python functions with Selenium API after exceeding page load time

I am currently working on a Python script that uses Selenium with the Chrome webdriver. Occasionally, the script gets stuck while loading pages because of JavaScript trying to load in the background. I have tried using the line: driver.execute_script("$(w ...

Unlock the Power of jQuery Hashing with the Addition of Additional Variables

Looking for a way to include an additional variable in a URL like the one above. I've experimented with different methods but I'm not certain which is the most effective. For example: Currently using JQUERY to detect the HASH value: if (window ...

Identifying a broken lock icon caused by a mix of secure and insecure content using JavaScript

Currently, I am in the process of ensuring that our website is fully functional under HTTPS. One important aspect of this is to prevent any occurrence of "breaking the lock." It is crucial not to load non-SSL content on an SSL page as this can result in a ...

Creating an Eye-catching Presentation: Tips for Adding Text to Your CSS3 Slideshow

I am currently in the process of creating a CSS3 slideshow with text for each image. I found inspiration from this example: . However, I made some modifications to make it responsive. Here is the HTML code I have used: <div id="slideshow"> < ...

Customize the appearance of each TreeItem in JavaFX using CSS to assign unique

I am looking for a way to color individual Tree Items in a treeView based on specific conditions. I found a promising answer, but unfortunately, I am struggling to implement it. You can check out the answer here. My main obstacle is understanding how to u ...

"Encountering a problem with posting API requests using Express

I've encountered a problem where I keep receiving a 404 error when trying to post to a specific route. Here's the code snippet: app.js (code snippet for app.js) .... module.exports = app; api.js (code snippet for api.js) .... module.export ...

Choose options from a dropdown menu by dragging and dropping them using jQuery

I have a situation where my PHP file generates a list of items on a webpage in an unordered format. I am looking to grab these items and place them into an array. My intention is to utilize the jQuery drag and drop feature, which can be seen in action in ...

Using jQuery to interact with an API

jQuery offers powerful methods such as getJSON, get, and load which ultimately involve making AJAX calls. My goal is to access the API provided by www.eventsinindia.com for events happening in Mumbai during May 2009. This API returns data in JSON format. ...

Why doesn't Select2 function properly in Bootstrap 3 when the tabindex is removed?

There is a bug with Select2 that causes it to malfunction in a Bootstrap 3 modal unless the tabindex element is removed. I have successfully resolved this issue in several modals on my page, but one specific modal still cannot get Select2 to function. Eac ...

Is Kendo Telerik grid capable of applying conditional formatting while filtering?

Is it feasible to modify the background color of rows in a Kendo Telerik grid when a filter is implemented within an ASP.NET MVC application? ...

"Troubleshooting: Issue with CSS code on Codepen when trying to create

I am attempting to replicate the Google logo using HTML and CSS. While the code functions properly in browsers, there seems to be an issue with Codepen not positioning the horizontal blue line correctly. How can this be resolved? What adjustments should ...

How come my MySQL date is decreasing by one day when using JavaScript?

My todo list is stored in a MySQL database with columns for todoTitle and todoDate. However, when I display the todoDate on my website, it shows the date decremented by one day. For example, if the date in the database is 2016-12-20, it will show as 2016-1 ...

A guide on utilizing the intl.formatRelativeTime() function effectively

I need to display messages like "created 1 hour ago" or "created 1 day ago," as well as in plural form, such as "created 10 minutes ago" or "created 3 days ago." To achieve this, I am attempting to utilize the FormatJS API, specifically the intl.formatRela ...

Delegating events with .on('click') and using the CSS negation selector :not()

Struggling to implement event delegation for a dynamically added or removed class? I need to create an event for elements that are clicked, but without a specific class. Here's the code I have so far, but it doesn't seem to be working. Could it b ...