简体   繁体   中英

Javascript click event requires double clicks

I have a simple HTML-CSS-JavaScript page with an event listener on a button to toggle a div.

However, all is working but the animation function takes two clicks first time to work, although i consoled the click event to prove that the button listens to the first click too.

i tried to wrap into window.onload but same thing.

note: i want to use pure javascript only. thank you

this pic shows the first click (it says "clicked" in the console):

首次点击后

this pic shows the second click (animation took place):

第二次点击后

Here is my code:

            var showDivButton = document.getElementById('showDivButton');
            var info =  document.getElementById('info');

            showDivButton.addEventListener('click', animation) ;

            // animation func
            function animation () { 
                console.log('Clicked!');
                if (info.style.display === 'none'){
                    info.style.display =  'inline-block';
                    showDivButton.style.background = 'green';
                } else {
                     info.style.display =  'none';
                     showDivButton.style.background = 'gray';
                }

            }

Look at My Plunker Here please. Thank you in advance.

Try to revise your function block as follow:

function animation () { 
    console.log('Clicked!');
    if (info.style.display == '' || info.style.display == 'none'){
        info.style.display =  'inline-block';
        showDivButton.style.background = 'green';
    } else {
         info.style.display =  'none';
         showDivButton.style.background = 'gray';
    }

}

info.style.display is '' on initial

Because info.style.display refers to the style attribute of your div, not the computed Style, so on the first click, this is not set.

You may want to look at getComputedStyle , but i would advise switching class instead of directly modifying style.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM