Adding and Removing Class Doesn't Occur JavaScript

<style>
  .rect {
            width: 50px;
            height: 50px;
            background: rgba(5, 172, 255, 0.5);
            display: inline-block;
            vertical-align: middle;
        }

        .animate {
            width: 50px;
            height: 50px;
            background: cyan;
            display: inline-block;
            vertical-align: middle;
</style>

       <div class="col-xs-2 col-md-2 col-lg-2">
                    <div class="rect" id="0"></div>

                </div>

                <div class="col-xs-2 col-md-2 col-lg-2">
                    <div class="rect" id="1"></div>

                </div>

                <div class="col-xs-2 col-md-2 col-lg-2">
                    <div class="rect" id="2"></div>

                </div>

                <div class="col-xs-2 col-md-2 col-lg-2">
                    <div class="rect" id="3"></div>
</div>


 var blink = function () {
            var randomNumber = Math.floor(Math.random() * 4);
            console.log(randomNumber);
            var selector = "#" + randomNumber;
            $(selector).removeClass("rect").addClass('animate')
    }
        setInterval(blink, 2000)

  1. Only One rectangle should turn to another color at a time.

  2. Suppose there are n Rectangles, Only 1 Rectangle should change color at a time that too Randomly. So I generated Random Function and Using it.

  3. After $(selector).removeClass(“rect”).addClass(‘animate’)

the above line the the rect is removed and animate is added and I want only for one rect in random this animate class should be added . And for every 200ms this should change.

Summary: I want a randomly showing blink effect (Changing Color is Ok) on 9 set of Rectangles.
I wanna use plain js and jquery.

I made up till the above code, and a minor part is left. Could anyone here help ?

As usual with this type of class switching, remove ‘animate’/add ‘rect’ for all rectangles, after that add ‘animate’/remove ‘rect’ for a random rectangle.

@Dormilich It isnt Working Like that, I tried even Toggle.

In your code you only work on the currently selected rectangle. but the previous state removal needs to be done on the previously selected rectangle.

also note that vertical-align does not have any effect in your setup.

Could you write that piece of Code, As I dint get that small thing.

I’ve got this fixed myself.

Thanks.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.