Transferring class titles between div elements

I would like to implement a feature where class names on div elements shift after a brief delay, perhaps 10 seconds.

My goal is for the 3 classes listed below to cycle through the div elements and start over once it reaches the last one.

For instance:

<div class="wrapper">
 <div></div>
 <div></div>
 <div class="previous-one"></div>
 <div class="in-focus"></div>
 <div class="next-one"></div>
 <div></div>
 <div></div>
</div>

would become:

<div class="wrapper">
 <div></div>
 <div></div>
 <div></div>
 <div class="previous-one"></div>
 <div class="in-focus"></div>
 <div class="next-one"></div>
 <div></div>
</div>

I hope this explanation is clear. This is my first post here, so let's kick things off with a challenge!

Thank you in advance for any feedback or suggestions.

Answer №1

One possible solution using jQuery is outlined below:

var colors = ['blue', 'green', 'red'],
    timer = 1000;

setInterval(function() {
  for(var c in colors) {
    var $current = $('.' + colors[c]),
        $next = $current.next('li');
    if($next.length == 0) {
      $next = $('ul li:first-child');
    }
    $current.removeClass(colors[c]);
    $next.addClass(colors[c]);
  }
}, timer);
.red {
  color: red;
}
.blue {
  color: blue;
}
.green {
  color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>lorem</li>
  <li class="blue">ipsum</li>
  <li class="green">dolor</li>
  <li class="red">hello</li>
  <li>world</li>
  <li>again</li>
</ul>

Answer №2

Consider each step carefully.

  • Locate all divisions within the container.
  • Eliminate the "previous-one" designation from the relevant item.
  • Swap "in-focus" with "previous-one".
  • Substitute "next-one" with "in-focus".
  • Determine if there is a subsequent element after in-focus.
    • If one exists, assign it as "next-one".
    • Alternatively, designate the initial division in the list as "next-one".
  • Repeat this process as needed.

http://example.com/jsfiddlelink123/

function updateDisplay() {
    var sections = $(".container div");
    var nextItem = sections.filter(".next-one");
    var activeItem = sections.filter(".in-focus");

    sections.filter(".previous-one").removeClass("previous-one");
    activeItem.removeClass("in-focus");
    activeItem.addClass("previous-one");
    nextItem.removeClass("next-one");
    nextItem.addClass("in-focus");

    var newNextItem = nextItem.next("div");
    if (newNextItem.length === 0) newNextItem = sections.first();
    newNextItem.addClass("next-one");
}

setInterval(updateDisplay, 1000);

Answer №3

My approach involves advancing each div by manipulating their classes. The next div gets the 'next-one' class while the current one has it removed. If the last div in the wrapper is reached, the class is moved to the first div. You can view the demo on this link.

Although the code may not be the most elegant, it functions effectively.

setInterval(function(){

    if($('.wrapper div').last()[0]==$('.next-one')[0]){
        $('.next-one').removeClass('next-one');
        $('.wrapper div').first().addClass('next-one');
    }
    else{
        $('.next-one').removeClass('next-one').next().addClass('next-one');
    }

    if($('.wrapper div').last()[0]==$('.previous-one')[0]){
        $('.previous-one').removeClass('previous-one');
        $('.wrapper div').first().addClass('previous-one');
    }
    else{
        $('.previous-one').removeClass('previous-one').next().addClass('previous-one');
    }

    if($('.wrapper div').last()[0]==$('.in-focus')[0]){
        $('.in-focus').removeClass('in-focus');
        $('.wrapper div').first().addClass('in-focus');
    }
    else{
        $('.in-focus').removeClass('in-focus').next().addClass('in-focus');
    }

},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

Unlocking the API endpoints within nested arrays in a React project

{ [ "quicktype_id": 1, "quicktype": "Laptops", "qucik_details": [ { "type_name": "car", "type_img": "car_img" }, { "type_name": "van", "type_img": ...

Retrieving a particular section within a <div> element from a webpage

I have been utilizing aiohttp and lxml for web scraping purposes to extract values from webpages. I have successfully implemented the following functions: def get_sr(page, tree): sr = tree.xpath(".//div[@class='competitive-rank']/div/text() ...

Please refrain from altering the color of my flag on hover

I am working with a table that has rows marked with flags. Below is the CSS I have used: <table class="hovered no-border" data-url="@Url.Action("General", "Transport")"> <tbody> <tr> <td><input type="che ...

Can XMLHttpRequest be exploited for XSS attacks?

Can cross-site scripting be achieved using an XMLHttpRequest as a post method? For instance, in a chatroom where users can enter text. Normally, inserting scripts like <script>alert("test")</script> would be blocked. However, you could write a ...

Ways to display scroll bar when hovering the mouse pointer?

When visiting the website YouTube, you may notice that their sidebar scrollbar becomes visible as soon as your mouse moves over it. I've been attempting to achieve this effect on my own div, but currently, the scrollbar only appears once I start scrol ...

Keeping Ajax active while the PHP script is running is essential

Seeking assistance with a specific issue. I currently have an ajax script (index.php) that sends variables to a php file (thumbs.php). The php file generates thumbnail images from original files and saves them on the server. This process can sometime ...

"Unleashing the power of custom servers to tap into the rendered HTML of Next

In my quest to serve a server-side generated page as a file using next.js, I decided to extract the rendered content within a custom server.js file: const express = require('express'); const next = require('next'); const port = parseIn ...

Hover over the text to disable the input element and display it as a textbox

Currently, I have a situation where I have two text boxes - when text is entered into textbox1, textbox2 becomes disabled as expected. However, my second requirement is that upon disabling textbox2, hovering over it should display the message "You can ente ...

The form validation in Bootstrap 5 seems to be having some trouble triggering

Here is the form setup for allowing users to change their account password: <div class="signup-form-small"> <form method="post" name="frmPassword" id="frmPasswo ...

Steps for accessing the "this" keyword within the parent function

Struggling with referencing `this` within a parent function while building a basic tab system using AngularJS. It seems like I may not have a solid grasp on the fundamentals, so any guidance would be appreciated: JavaScript: $scope.tabs = { _this: th ...

Modifying an item in a list using React and Redux

I am facing an issue with my table that consists of 50 rows, each representing an item from a list. When I click on a checkbox within a row, I want to mark that specific item as selected. However, the problem is that clicking on any checkbox causes all 50 ...

Monitoring the sharing of content on social media networks, rather than tracking individual

After setting up a hidden page on my site and configuring buttons to test pushing data to the dataLayer, I have ensured that my Google Tag Manager (gtm) is functioning properly. I recently tracked a Google +1 button click successfully, confirming that my c ...

Analyzing the path of the cursor

Looking to enhance my tracking capabilities by monitoring mouse movements. I have the ability to capture XY coordinates, but understand that they may vary depending on browser size. Are there any other parameters recommended for accurate results? P.S: Be ...

A versatile function that displays a loading icon on top of a specified div

Is it possible to pass an identifier for a particular div element to a function, where the function will display a loading image that covers the entire div, and then pass the same identifier to another function to hide the loading image? I am looking to cr ...

What methods can be used to cloak JavaScript functions from the end user?

Looking to utilize jQuery AJAX calls? Here's an example: function addNewTeacher(){ $.ajax({ type: "POST", url: "/actions/dboss/newteacher.php", data: "uname=" + $("#newteacheruname").val() + "&upass=" + $("#new ...

Express is unable to locate the specified property

Here is my controller code snippet: exports.showit = function(req, res){ res.render('showpost', { title: req.post.title, post: req.post }) } In my post model, I have included title and name objects: title: {type : String, default : &apos ...

Utilizing a function argument within the :not() selector

I am currently working towards the objective of selecting all elements in my document except for those within a specific class. This is what I have come up with so far: var x = document.querySelectorAll(":not(.myParameter)"); My aim is to make 'myPa ...

Using javascript to quickly change the background to a transparent color

I am in the process of designing a header for my website and I would like to make the background transparent automatically when the page loads using JavaScript. So far, I have attempted several methods but none seem to be working as desired. The CSS styles ...

$http promise chain executing in an incorrect sequence

As a beginner in angularjs, my objective is straightforward. I aim to execute an ajax request to fetch data and, upon completion, I want to initiate a second call to retrieve another set of data based on the information from the initial set. To achieve th ...

The proper approach is using CSS for linking pseudo-classes

Look what I stumbled upon: Important: Remember, a:hover MUST be placed after a:link and a:visited in the CSS code to work properly!! Remember: Place a:active after a:hover for it to have an effect in the CSS code!! Note: Pseudo-class names are not case- ...