javascriptdebuggingaddeventlistenerselectors-api

javascript addEventListener by querySelector not work


HI this is my javascript code :

window.onload = function () {

    function hideAds() {
        setTimeout(hide, 2000);
    }

    function hide() {
        var ads = document.querySelector(".ads");
        ads.style.marginTop = (-ads.offsetHeight) + "px";
    }

    function reveal() {
        ads.style.marginTop = "";
        hideAds();
    }
    var ads = document.querySelector(".ads");
    ads.addEventListener("click", reveal, true);


    hideAds();

}

from this code, everything work fine other then "ads.addEventListener" second line from last. what is the reason? is i made anything wrong here..?

i need to call my reveal function by click the ads class added div.

any one help me?


Solution

  • The code you gave should work as it is. jsFiddle

    But I'd be tempted to re-factor your code like so.

    HTML

    <div class="ads">Blah blah blah</div>
    

    Javascript

    function setMarginTop(element, marginTop) {
        element.style.marginTop = marginTop || null;
    }
    
    function hideAds(element, marginTop, ms) {
        setTimeout(function() {
            setMarginTop(element, marginTop);
        }, ms || 2000);
    }
    
    window.addEventListener('load', function () {
        var ads = document.querySelector('.ads'),
            hide = (-ads.offsetHeight) + 'px';
    
        hideAds(ads, hide);
        ads.addEventListener('click', function (evt) {
            var target = evt.target;
    
            setMarginTop(target)
            hideAds(target, hide);
        }, false);
    }, false);
    

    On jsFiddle