Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder
    Join Date
    Apr 2010
    Posts
    418
    Thanks
    4
    Thanked 1 Time in 1 Post

    Unable to change class value via dom

    This is the line in my html...

    <i id="displayMenuIcon" class="fa fa-bars"></i></a>



    and this is my JS that I have tried to get the icon to toggle.

    var toggle= 1;
    startIt();

    function startIt() {
    var icon = document.getElementById("displayMenuIcon");
    // alert(icon.class);
    if (toggle> 2) {toggle= 1}
    if (toggle== 1) {
    icon.class = 'fa-bars';
    // alert(1);
    } else {
    icon.class = 'fa-paw';
    // alert(2);
    }
    toggle++;
    setTimeout(startIt, 2000); // Change image every 2 seconds
    }

    As far as I can tell all works as I tried it with the alerts and it shows them ok, but I can not get the class value to change. It does show the content of the class in the first alert but it does not get changed. Can someone see what am I missing or doing wrong?

  2. #2
    Senior Coder coothead's Avatar
    Join Date
    Jan 2004
    Location
    chertsey, a small town 25 miles south west of london, england.
    Posts
    3,264
    Thanks
    1
    Thanked 552 Times in 538 Posts
    Hi there jasonpc1,

    try it like this...

    Code:
    
    <script>
    (function( d ) {
        'use strict';
        var  icon = d.getElementById( 'displayMenuIcon' ),delay = 2000;
    
    function startIt() {
    if ( icon.classList == 'fa fa-bars' ) {
         icon.classList.remove ( 'fa-bars' );
         icon.classList.add ( 'fa-paw' );
       } else {
         icon.classList.remove ( 'fa-paw' );
         icon.classList.add ( 'fa-bars' );	
       }
     }
         setInterval( startIt, delay ); 
    }( document ));
    </script>
    

    coothead
    Last edited by coothead; Jul 11th, 2018 at 10:22 PM.
    ~ the original bald headed old fart ~


 

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •