Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute different code upon second click (JavaScript)

My problem is that I've been working on a "accordion menu", which uses CSS3 transition on the height property to give it an animation when the <li> is expanding, which contains a submenu.

The expansion of the <li> happens when calling a function, triggered by a onclick event. The function calculates the new height for the containing <li> based on how many <li>'s the submenu contains. All this works fine, but I can't figure out how to reset the height on the second click, to close the submenu.

function accordion(ul){
    {
    // Make new height happen
    var howManyChildren = document.getElementById(ul).children.length;
    var calcSubHeight = 30 + howManyChildren * 31 + 'px'; // "top-padding" + amount of <li>'s * each <li> height + unit
    var elementId = ul.replace('_ul','');
    document.getElementById(elementId).style.height = subHeight;
    }
    else // Code to be executed on secound click.
    {
    document.getElementById(elementId).style.height = "";
    }
}

I want the "else" block to execute on the second click, as the comment states. So I might have been a bit to elaborate here. And pardon for the bad English, I'm quite Swedish.

like image 525
Leif Thorén Avatar asked Apr 12 '26 01:04

Leif Thorén


1 Answers

Try this, it sees if the height returns false.

function accordion(ul) {
    var elementId = ul.replace('_ul', '');
    if (!document.getElementById(elementId).style.height) {
        var howManyChildren = document.getElementById(ul).children.length;
        var calcSubHeight = 30 + howManyChildren * 31 + 'px'; // "top-padding" + amount of <li>'s * each <li> height + unit
        document.getElementById(elementId).style.height = subHeight;
    } else {
        document.getElementById(elementId).style.height = "";
    }
}
like image 109
howderek Avatar answered Apr 13 '26 15:04

howderek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!