locked
How To: Cycle 2 different Classes on a label to make it flash. RRS feed

  • Question

  • User-224188520 posted

    Hey All,

    I think this is simple but I've stumbled trying to find a simple solution, a lot of timer solution out there with a lot of code that are not exactly what I am looking for.

    I am just looking to rotate on a timer the class of a label to change the color, here are my label examples.

    Start with: <span id="loginLabel" class="label label-danger">

    Change to after 2 seconds: <span id="loginLabel" class="label label-warning">

    Then repeat the process indefinitely.

    Thanks,

    Monday, March 12, 2018 4:02 PM

Answers

  • User475983607 posted

    An example of toggling CSS using jQuery.

    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Demo</title>
    
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous" />
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous" />
    </head>
    <body>
        <span id="loginLabel" class="label label-danger">Login</span>
    
        <script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
        <script>
    
            //timer fires every 2 seconds
            setInterval(toggleloginCss, 2000);
    
            //toggle css
            function toggleloginCss() {
    
                if ($('#loginLabel').hasClass('label-danger')) {
                    $('#loginLabel').removeClass('label-danger');
                    $('#loginLabel').addClass('label-warning');
                }
                else {
                    $('#loginLabel').removeClass('label-warning');
                    $('#loginLabel').addClass('label-danger');
                }
            }
        </script>
    </body>
    </html>

    References

    https://www.w3schools.com/jsref/met_win_setinterval.asp

    https://api.jquery.com/category/selectors/

    https://api.jquery.com/hasclass/

    https://api.jquery.com/addclass/

    https://api.jquery.com/removeclass/

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, March 12, 2018 4:57 PM