Welcome to PhoneASK, where you can ask questions and receive answers from other members of the community.

Jquery Addclass/Removeclass in specific order based on id attribute

asked 8 days ago by Caesar

I'm attaching an addClass to a group of elements with the same class. However, I need it to be done in a specific order based on the ID attribute. I've been trying a for loop and the addClass based on the element with the ID at the loop number. However, this ends up applying the addClass at all once and I need it to do it one at a time based on the loop. How can I achieve this?

Originally I thought I could addClass, delay/setTimeOut, then removeClass, but no matter what I try, it seems to just want to apply to all elements at once when my desired affect is to loop through the IDs individually and addClass, delay, removeClass.

$("li.all-floors[id='1']").removeClass("on-floor");
 for (var i = 1; i <= floorValueNum; i++) {                                     

setTimeout(function() {
    	$("li.all-floors[id=" + (i-1) + "]").addClass("on-floor");
}, 1000);

            }
.on-floor{
    
    color: red;
           
}

.housing-floor {
    margin: 0;
    padding: .25em 2em;
    border-top: 2px solid #FFFFFF;
    text-align: center;
    line-height: 1em;
    font-size: .75em;
    text-align: center;
    color: black;
    font-weight: bold;
        -webkit-transition: all 0.3s ease;
    -moz-transition: all 0.3s ease;
    -o-transition: all 0.3s ease;
    transition: all 0.3s ease;
}
.activity-floor {
    margin: 0;
    padding: .4em 2em;
    border-top: 2px solid #FFFFFF;
    text-align: center;
    line-height: 1.5em;
    font-size: .75em;
    text-align: center;
    color: black;
    font-weight: bold;
        -webkit-transition: all 0.3s ease;
    -moz-transition: all 0.3s ease;
    -o-transition: all 0.3s ease;
    transition: all 0.3s ease;
}

.activity-floor-group, .housing-floor-group{
    list-style: none;
    padding: 0;
    margin: 0;
  float:left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<ul class= "housing-floor-group">
              <li class="housing-floor all-floors" id="42">42</li>
              <li class="housing-floor all-floors" id="40">40</li>
              <li class="housing-floor all-floors" id="38">38</li>
              <li class="housing-floor all-floors" id="36">36</li>
              <li class="housing-floor all-floors" id="34">34</li>
              <li class="housing-floor all-floors" id="32">32</li>
              <li class="housing-floor all-floors" id="30">30</li>
              <li class="housing-floor all-floors" id="28">28</li>
              <li class="housing-floor all-floors" id="26">26</li>
              <li class="housing-floor all-floors" id="24">24</li>
              <li class="housing-floor all-floors" id="22">22</li>
              <li class="housing-floor all-floors" id="20">20</li>
              <li class="housing-floor all-floors" id="18">18</li>
              <li class="housing-floor all-floors" id="16">16</li>
              <li class="housing-floor all-floors" id="14">14</li>
              <li class="housing-floor all-floors" id="12">12</li>
              <li class="housing-floor all-floors" id="10">10</li>
              <li class="housing-floor all-floors" id="8">08</li>
              <li class="housing-floor all-floors" id="6">06</li>
            </ul>
            <ul class= "housing-floor-group">
              <li class="housing-floor all-floors" id="43">43</li>
              <li class="housing-floor all-floors" id="41">41</li>
              <li class="housing-floor all-floors" id="39">39</li>
              <li class="housing-floor all-floors" id="37">37</li>
              <li class="housing-floor all-floors" id="35">35</li>
              <li class="housing-floor all-floors" id="33">33</li>
              <li class="housing-floor all-floors" id="31">31</li>
              <li class="housing-floor all-floors" id="29">29</li>
              <li class="housing-floor all-floors" id="27">27</li>
              <li class="housing-floor all-floors" id="25">25</li>
              <li class="housing-floor all-floors" id="23">23</li>
              <li class="housing-floor all-floors" id="21">21</li>
              <li class="housing-floor all-floors" id="19">19</li>
              <li class="housing-floor all-floors" id="17">17</li>
              <li class="housing-floor all-floors" id="15">15</li>
              <li class="housing-floor all-floors" id="13">13</li>
              <li class="housing-floor all-floors" id="11">11</li>
              <li class="housing-floor all-floors" id="9">09</li>
              <li class="housing-floor all-floors" id="7">07</li>
            </ul>
            <ul class="activity-floor-group">
                <li class="activity-floor all-floors" id="5">Pool</li>
                <li class="activity-floor all-floors" id="4">Gym</li>
                <li class="activity-floor all-floors" id="3">Restaurant</li>
                <li class="activity-floor all-floors" id="2">Meeting Rooms</li>
                <li class="on-floor activity-floor all-floors" id="1">Lobby</li>
      </ul>

Your answer

4 Answers

answered 7 days ago by Pakka Pakka

Here is one way to do to it:

Create a recursive function and set a small delay via setTimeout()

$(document).ready(function(){


    // Use a counting variable to run through ids: (.all-floors #<1,2,3...>)
    // This method lets you run the animation in order, without sorting.
    var intervalCount = 1;
    var totalObjects = $(".all-floors").length;

    // Iterate through the all-floors objects, one-by-one via recursion
    function animateNextItem(){

        if (intervalCount >= totalObjects) return;

        // Grab the element according to its id number
        var element = $("#"+intervalCount);

        // If the element is an actual all-floor object
        if (element && element.hasClass("all-floors")){

            // add the class
            element.addClass("on-floor");

            // Set timer on when to remove the class, increase the 
            // intervalCount and call this function again
            setTimeout( function(){
                element.removeClass("on-floor");
                intervalCount++;
                animateNextItem();
                }, 500);    

        } else {

            // If you get here, it means that there wasn't an
            // .all-floors object with an id = intervalCount. So 
            // increase the intervalCount by one and try again
            intervalCount++;
            animateNextItem();  
        }
    }

    // Start the whole process here
    animateNextItem();

});

SEE THE CODE IN ACTION ON JSFIDDLE

Basically, you use a counting variable to run through the list of id's in order, and call a recursive function to apply/remove the classes via the setTimeout() function. If you copy and past this code into your file, you should see that the elements "animate in" and then "animate out" in order. Doing things this way assumes that you assign a unique number to each of the elements, but will still work even if you skip an index (say you assign #1 and #3, but forgot to assign #2, it will still work). This saves you from having to grab each element, add them to an array, and then sort the array based on id number to animate things in order. It also gives you the freedom to control the timing of the animation by adjusting the timer on the setTimeout() function.

answered 7 days ago by RaviRanjankr

For addClass use :

var css={ opacity : 120 };
$("li.all-floors[id=" + (i-1) + "]").addClass("on-floor").animate(css, 1000);

For removeClass use :

var css={ opacity : 0 };
$("li.all-floors[id=" + (i-1) + "]").removeClass("on-floor").animate(css, 1000);
answered 6 days ago by tyranid

You should probably remove the class from all the li elements before you start applying them in a loop, instead of just one element.. $("li.all-floors[id='1']").removeClass("on-floor"); Try,

$("li").removeClass("on-floor");

Oh yea and make sure to increment your time by one second in each iteration. :)like so,

setTimeout(function() {
    $("li.all-floors[id=" + (i-1) + "]").addClass("on-floor");
}, 1000 * i);

For the effect to be seen to be applied in order fashion.

answered 6 days ago by knbk

try this script:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $("li.all-floors[id='1']").removeClass("on-floor");
        var floorValueNum = 10;
        for (var i = 1; i <= floorValueNum; i++) { 
            add(i);
        }
        function add(i) {
            setTimeout(function() {$("li.all-floors[id=" + (i-1) + "]").addClass("on-floor");}, 1000 + i * 1000);
        }
    });
</script>

<style>
.activity-floor-group .on-floor{
    color: red;
}

.housing-floor {
    margin: 0;
    padding: .25em 2em;
    border-top: 2px solid #FFFFFF;
    text-align: center;
    line-height: 1em;
    font-size: .75em;
    text-align: center;
    color: black;
    font-weight: bold;
        -webkit-transition: all 0.3s ease;
    -moz-transition: all 0.3s ease;
    -o-transition: all 0.3s ease;
    transition: all 0.3s ease;
}
.activity-floor {
    margin: 0;
    padding: .4em 2em;
    border-top: 2px solid #FFFFFF;
    text-align: center;
    line-height: 1.5em;
    font-size: .75em;
    text-align: center;
    color: black;
    font-weight: bold;
        -webkit-transition: all 0.3s ease;
    -moz-transition: all 0.3s ease;
    -o-transition: all 0.3s ease;
    transition: all 0.3s ease;
}

.activity-floor-group, .housing-floor-group{
    list-style: none;
    padding: 0;
    margin: 0;
  float:left;
}
</style>
</head>
<body>

<ul class="housing-floor-group">
              <li class="housing-floor all-floors" id="42">42</li>
              <li class="housing-floor all-floors" id="40">40</li>
              <li class="housing-floor all-floors" id="38">38</li>
              <li class="housing-floor all-floors" id="36">36</li>
              <li class="housing-floor all-floors" id="34">34</li>
              <li class="housing-floor all-floors" id="32">32</li>
              <li class="housing-floor all-floors" id="30">30</li>
              <li class="housing-floor all-floors" id="28">28</li>
              <li class="housing-floor all-floors" id="26">26</li>
              <li class="housing-floor all-floors" id="24">24</li>
              <li class="housing-floor all-floors" id="22">22</li>
              <li class="housing-floor all-floors" id="20">20</li>
              <li class="housing-floor all-floors" id="18">18</li>
              <li class="housing-floor all-floors" id="16">16</li>
              <li class="housing-floor all-floors" id="14">14</li>
              <li class="housing-floor all-floors" id="12">12</li>
              <li class="housing-floor all-floors" id="10">10</li>
              <li class="housing-floor all-floors" id="8">08</li>
              <li class="housing-floor all-floors" id="6">06</li>
            </ul>
            <ul class="housing-floor-group">
              <li class="housing-floor all-floors" id="43">43</li>
              <li class="housing-floor all-floors" id="41">41</li>
              <li class="housing-floor all-floors" id="39">39</li>
              <li class="housing-floor all-floors" id="37">37</li>
              <li class="housing-floor all-floors" id="35">35</li>
              <li class="housing-floor all-floors" id="33">33</li>
              <li class="housing-floor all-floors" id="31">31</li>
              <li class="housing-floor all-floors" id="29">29</li>
              <li class="housing-floor all-floors" id="27">27</li>
              <li class="housing-floor all-floors" id="25">25</li>
              <li class="housing-floor all-floors" id="23">23</li>
              <li class="housing-floor all-floors" id="21">21</li>
              <li class="housing-floor all-floors" id="19">19</li>
              <li class="housing-floor all-floors" id="17">17</li>
              <li class="housing-floor all-floors" id="15">15</li>
              <li class="housing-floor all-floors" id="13">13</li>
              <li class="housing-floor all-floors" id="11">11</li>
              <li class="housing-floor all-floors" id="9">09</li>
              <li class="housing-floor all-floors" id="7">07</li>
            </ul>
            <ul class="activity-floor-group">
                <li class="activity-floor all-floors" id="5">Pool</li>
                <li class="activity-floor all-floors" id="4">Gym</li>
                <li class="activity-floor all-floors" id="3">Restaurant</li>
                <li class="activity-floor all-floors" id="2">Meeting Rooms</li>
                <li class="activity-floor all-floors" id="1">Lobby</li>
      </ul>

</body>
</html>

Related Questions

i have this code, i mean i have 2 size data and 2 price data on link element like this <a class=thumb href= data-size1=All Size data-size2=25cm - 15cm data-price1=IDR 60,000 data-price2=
I have an element with id=A B. The following code fails: <input type=text id=A B> <script>$(#A B).click(function(){alert();});</script> The following code does not fail: <
I have the following code <a class=getty id=1 href=/...>One<./a> <a class=getty id=2 href=/...>Two<./a> <a class=getty id=3 href=/...>Three<./a>
I need your help. This code works fine for me: <div class=grauereihe> <div class=kleinesbild> <a data-lightbox=ags1 class=bildtopa href=images/image1.jpg> <img class=bi
Hey I am looking to create an order reference which is something like this PLC0000001 Where the 1 would be my order id but lets say it gets to 100 would like PLC0000100 In VB.NET how could I build up
I am trying to pull the data out from a table row so that it can be updated, but I am really confused as to why it is not happening. Below is a snippet of generated HTML. The record ID is held in the
I've got the following scenario: var el = 'li'; and there are 5 <li>'s on the page each with a data-slide=number attribute (number being 1,2,3,4,5 respectively). I now need to find the currentl
I cant seem to understand what i'm doing wrong here. To certain extend my code does work but instead of finding the id of the clicked element, it finds all the ids http://jsfiddle.net/34a5b/ - I put i
I have two tables and I want to highlight a cell in table 1 when I hover over another cell in table 2. Not sure how to get there from here. I'm thinking I should take the id from table 2 and look for
I want to check all checkboxes based on Div ID and Checkbox Class. All checkboxes in different divs have the same class. I want to check all checkboxes on button click which is in that particular div.
I want to have it so that clicking one element affects a different one, based on some kind of reference stored in the clicked element. I have the following script, but it doesn't seem to be running pr
Is it possible to replicate this kind of specific sql ordering in the django ORM: order by (case when id = 5 then 1 when id = 2 then 2 when id = 3 then 3 when id = 1 then 4 when id = 4 then 5 end) asc
Ok, I asked something similar before, but I've researched it and haven't found this specifically. I have a table that I need sorted on fields OptionName(NVarChar) and IsActive(BIT). I need the results
I Have a table called Results and the data looks like: Response_ID Label 12147 It was not clear 12458 Did not Undersstand 12458 Was not resolved 12458 Did not communicate 12586 Spoke too fast 12587 To
I am trying to remove the last character from a div id using jQuery. Currently I have: <div id=foo/></div> But I need: <div id=foo></div> The character is always a / an
I'm building a website and I have an unsorted list with some list elements. When I click on some of these list items I want my <body>’s id to change from id=index to id=collection. What's th
How can I get a specific row (id=x) and then the reminders? Something like: SELECT * FROM table ORDER BY id=5 FIRST THAN id DESC I tried to use UNION ALL, like: (SELECT * FROM table WHERE id=5) UNION
I'm looking to change the class (hide) of certain div's dependent on their attribute values.Here's my code, it might make a bit more sense once you've seen this: jQuery('#menu1').click(function() { jQ
I have a bunch of RSpec Rake tasks defined that I'd like to run in a specific order when I run the entire suite of tests. I've tried something like this: task :run_in_order => [:one, :two, :three
There are several times in C in which a type is guaranteed to be at LEAST a certain size, but not necessarily exactly that size (sizeof(int) can result in 2 or 4). However, I need to be absolutely cer
This is my buttons: <button id=add>Add</button> <button id=remove>Remove</button> this is my JavaScript code: <script type=text/javascript> $(document).ready(funct
I'm trying to get the source attribute of all images withing a specific div but somehow it keeps telling me that the function .attr() doesn't exist... That's the function. Firebug also tells me that
i am use $(expr).attr(hash,value) to set a hash attribute for HTML anchor element a but the Jquery would not do that. but if i change expr to div, then i can set hash attribute to div tag.
Can I count the number of elements with a specific attribute? For example all the images with the src attribute test.gif
Background I've got a couple of jQuery functions that set a search field to contain the word Search and clear it / reset it when the field is clicked in and out of.... // Search Box Placeholder jQue
At 4 minutes into the Scroll Linked Navigation podcast Posted: Wed, 18 Aug 2010 at jQuery for Designers, Remy uses the hash attribute. Q: Where is the hash attribute documented?
I have the following table: <table id=test> <tr id=1><td>bla</td></tr> <tr id=2><td>bla</td></tr> <tr id=3><td>bla</td></tr
This is essentially the same question as CakePHP: Is it possible to insert record with pre-defined primary key value?. In CakePHP 1.2 I want to insert a record with a pre-determined id. The id's value
I have a feeling I'm missing something obvious, but... All my neat jQuery functions are being forced to wait by a particularly slow-moving javascript api call from within the body of the page. I'd lik
using jQuery I'd like to load a local html file first ( which contains a spesific id element ) right after that I'd like to run a jQuery plugin to work on the spesific id element that is loaded from t
I have a id based CSS file where I noticed I'm mostly repeating myself. What I'd like to do is specify that an item with an id follows a certain class + some other rules. For example: I'd like id id1
I use Pagedown which requires to give id of wmd-input to textarea. It is written as the following in Markdown.Editor.js: function PanelCollection(postfix) { this.buttonBar = doc.getElementById(wmd-bu
I'm using the jquery quicksand plugin. I need to get the data-id of the clicked item and pass it to a webservice. How do I get the data-id attribute? I'm using the .live() method to re-bind the click
I am trying to set the data-id and/or value of a span from my js file after a click event. <span id=test></span> my sudo code js file nextLink: function(event) { $('#test').val = 3; $(
I'm in the process of teaching myself Ruby and Nokogiri. I have an nmap scan, output as below: <host starttime=1368204336 endtime=1368204506><status state=up reason=arp- response reas
Having a major brain freeze, I have the following chunk of code: // Get web address $domQuery = query_HtmlDocument($html, '//a[@class=productLink]'); foreach($domQuery as $rtn) { $web = $rtn->get
Using Python ElementTree to construct and edit test messages: Part of XML as follows: <FIXML> <TrdMtchRpt TrdID=$$+TrdID# RptTyp=0 TrdDt=20120201 MtchTyp=4 LastMkt=ABCD LastPx=104.
What is the fastest way to find whether the current node is in path of a node with a specific attribute, given this xml structure: <root> <item> <item name=x> <item></item
I am trying to parse an XML file from a URL by taking all <Type> elements where is parameter type_id=4218?? XML document: <BSQCUBS Version=0.04 Date=Fri Dec 9 11:43:29 GMT 2011 Machin
I want to make a dropdown menu, so that when anywhere on the page but the dropdown menu or the links leading to them are clicked, the dropdown is hidden. Jquery: $('body:not(#top-links-bar)').click(fu
I'm still learning jQuery and I ran into a problem. I have a table with 50+ rows. Each is labeled with an id. <tr id=51> This id is the database id and I need to pass it to jQuery and submit
I am trying to build an Infopath form which populates fields with data back from a Sharepoint list. I set up a drop-down list box who's values get populated from a Sharepoint data source. That part wo
I'm using an STL std::multiset<> as a sorted list of pointers. The sort order is determined by a property of the items being pointed to, something along the lines of this simplified example: str
I want to merge the position elements and create a new element called travel after comparing the type attribute. First type=from has to merge with first type=to found and should continue with the
We are using Magento for our eCommerce site. Our products have custom attributes on the backend that we use to display product specific information. Our products are displayed with jquery .accordion &
Need help in parsing the following XML. I am a newbie to Linq to XML. I want to parse all picture data in a single objects array, and I dont seem to find a way, Here is a sample xml, <Object type=
I'm building an angular directive which will be in multiple places on the same page. I've got a few different video tags, and want to build something flexible enough that I can place the right video i
Is it possible to define in XML Schema an condition based on attribute value? For example, when test@attrib=one, I want one-element to be allowed and mandatory or when test@attrib=two, I want two-
I have two selects: SELECT id FROM a -- returns 1,4,2,3 UNION SELECT id FROM b -- returns 2,1 I'm receiving correct num of rows, like: 1,4,2,3. But I want b table results first: 2,1,4,3 or 2,1,3,4 Ho
I have a table that holds days and times, the day column, can have any of the seven days entered into it, and they are set to data type varchar. As this table holds booking times for a client, I want
...