Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using JS to Switch CSS Styles

Status
Not open for further replies.

theVille

Technical User
Nov 27, 2006
4
GB
I'm trying to get JS to swap the style class on my webpage. The following almost works. Basically it is initiated using 'onClick' in the HTML. The class is (in most cases) set to 'hide'. You click on it and the JS changes the class to 'show'. This works. Problem is, if I set the initial html to 'show' the JS doesn't work until the object is clicked more than once.


menu_status = new Array();

function showHide(target){
var switch_id = document.getElementById('submenu_'+target);
if(menu_status['submenu_'+target] == 'show') {
switch_id.className = 'hide';
menu_status['submenu_'+target] = 'hide';
}else{
switch_id.className = 'show';
menu_status['submenu_'+target] = 'show';
}
}
 
It's because your array doesn't have any initial status set, so when it evaluates the if clause, it's always false until a value gets set. A quick and sloppy solution to this problem is to set it such that the else condition is the one that you always want to trigger first. For example, if the element is by default shown on the page, make the else clause hide the element - or if it is by default hidden, make the else clause show the element. I'm assuming from the code that you posted above that the element is shown by default, because the else clause makes the element visisble. So, swap the logic in the if clause to make it work:
Code:
menu_status = new Array();

function showHide(target){
    var switch_id = document.getElementById('submenu_'+target);
        if(menu_status['submenu_'+target] == [!]'hide'[/!]) {
           switch_id.className = [!]'show'[/!];
           menu_status['submenu_'+target] = [!]'show'[/!];
        }else{
           switch_id.className = [!]'hide'[/!];
           menu_status['submenu_'+target] = [!]'hide'[/!];
    }
}

-kaht

Looking for a puppy? [small](Silky Terriers are hypoallergenic dogs that make great indoor pets due to their lack of shedding and small size)[/small]
 
I've changed the 'if' statement as follows so that it gets the status directly from the html and it now works.

Thanks.



if(document.getElementById('submenu_'+target).className == 'show') {
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top