简体   繁体   中英

javascript onclick event not firing on first click

The code below is a link which when clicked will open & close an initially hidden div. It works fine other than having to click the link twice in the first instance to open it. It's not a major problem but if it can be made so that the div opens on the first click that would be great. Thanks

toggleDiv.js

function toggleDiv(elem, eventType, handler) {
    if (elem.addEventListener) {
        elem.addEventListener(eventType, handler, false);
    } else {
        elem.attachEvent('on' + eventType, handler);
    }
}

toggleDiv(window, 'load', function() {
    var link = document.getElementById('myMagicLink'),
        div = document.getElementById('foo');
    toggleDiv(link, 'click', function() {
        if (!link) return true;
        if (div.style.display == "none") {
            div.style.display = "block"
        } else {
            div.style.display = "none"
        }
        return true;
    });
});

index.html

<body>
<a id="myMagicLink" href="http://www.google.com/">My Magic Link</a>
<div id="foo">Opens a div</div>
<br>
End of page
<br>
<script language="JavaScript" type="text/javascript" src="toggleDiv.js"></script>
</body>

I had the same problem for toggling the display value of an ASIDE tag. Switching from "none" to "inline" and back again would not work on the first click. Display was set to "none" in my CSS file. In my script I changed "none" to "" (which seems to mean "default" as far as I understand). The following code works fine for me now.

    var x = document.getElementsByTagName("aside")[0];
if (x.style.display == "")
{
    x.style.display = "inline"; 
}
else
{
    x.style.display = "";   
}

I understood this when I saw the CSS/actual values in Firefox developer tools: "aside" is shown with CSS attributes, but an "element" is first shown with no attribute. On first click, "element" was assigned a "display" attribute set to "none".

Not sure what the trouble you are having this... this works flawlessly for me in Chrome.

I did change the url of your link to reflect back to the same document, but the div foo is hiding and reappearing as it should.

Couple of style notes: Rather than setting display = "block" it is better to say display = "" so it can return to its default value.

In addition, I also included a preventDefault function. Your use of return true would work for DOM0 style event handling, but it did not work with the attachEvent/addEventHandler code. This properly keeps the link from being followed.

<html>
<head>
<title>Test</title>
<script>
function toggleDiv(elem, eventType, handler) {
    if (elem.addEventListener) {
        elem.addEventListener(eventType, handler, false);
    } else {
        elem.attachEvent('on' + eventType, handler);
    }
}


toggleDiv(window, 'load', function() {
    var link = document.getElementById('myMagicLink'),
        div = document.getElementById('foo');
    toggleDiv(link, 'click', function(e) {
        if (!link) return cancelDefaultAction(e);

        if (div.style.display == "none") {
            div.style.display = "block"
        } else {
            div.style.display = "none"
        }       
        return cancelDefaultAction(e);
    });
});

function cancelDefaultAction(e) {
 var evt = e ? e:window.event;
 if (evt.preventDefault) evt.preventDefault();
 evt.returnValue = false;
 return false;
}   

</script>


<body>
<a id="myMagicLink" href="#">My Magic Link</a>
<div id="foo">Opens a div</div>
<br>
End of page
<br>

</body>
</html>

Sorry it seems a bit complicated for something pretty simple, unless you have a specific design in mind; but this should work equally well:

The Fiddle

<html>
<head>
    <script language="JavaScript" type="text/javascript">

    var toggled = false;
    function toggleDiv()
        {
           if(toggled)
             {
               document.getElementById('foo').style.display = '';
               toggled = false;            
             }       
           else
           {
               document.getElementById('foo').style.display = 'none';
               toggled = true;
           }
        }
    </script>
    </head>
<body>
<a id="myMagicLink" href="http://www.google.com/" onClick='toggleDiv()'>My Magic Link</a>
<div id="foo">Opens a div</div>
<br>
End of page
<br>
</body>
</html>

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