简体   繁体   中英

'OnClick' function not running on first click, a second click is required

So, I have a pair of elements that have an onClick function known as timeline1(). However, the script does not run when the div is clicked the first time, yet runs fine after an additional click. Below is the HTML code:

<div class="Section_Timeline_Bullet">
            <div class="Section_Timeline_Bullet_Connector"></div>
            <img src="images/RightArrow.png" id="RightArrow1" onclick="timeline1()">
            <div class="Section_Timeline_Bullet_Info" id="Info1" onclick="timeline1()">12/02/2019</div>
        </div>

and this is the corresponding Javascript function that should be running from the first click:

function timeline1() {
var arrow1 = document.getElementById('RightArrow1');
var info1 = document.getElementById('Info1');

if (info1.style.height == "5vh") {
    arrow1.classList.add("Section_Timeline_Rotated_Image_Up");
    arrow1.style.transition = "all 0.5s ease";
    arrow1.style.left = "-0.65vw";
    info1.style.top = "-42vh";
    info1.style.height = "20vh";
    info1.style.transition = "all 0.5s ease";
} else {
    arrow1.classList.remove("Section_Timeline_Rotated_Image_Up");
    arrow1.style.transition = "0";
    arrow1.style.left = "-0.5vw";
    info1.style.height = "5vh";
    info1.style.top = "-27vh";
    info1.style.transition = "0";
}

}

The only thing that the arrow1.classList.add("Section_Timeline_Rotated_Image_Up); part does is rotate the image, which still does not run on the first click of the div as well. Any help as to why the function doesn't run on the first click, but does on the second would be appreciated.

TL;DR : Clicking on element doesn't run its onClick the first time, but clicking again runs it fine... Help D:

Your script actually does indeed trigger the first time. The problem is that your info1 element doesn't have a height of 5vh by default , so the function falls into the else condition the first time it is run. To correct this, either set info1.style.height = "5vh" before invoking the function for the first time, or set the desired 'first click' behaviour in the else conditional.

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