Javascript addEventListener on request Selector not work

HI 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 works fine, and then "ads.addEventListener" the second line from the last. what is the reason? did i do something wrong here ..?

I need to call the expansion function by clicking the ad class added by the div.

Does anyone help me?

+4
source share
1 answer

The code you provided should work as it is. jsFiddle

But I will be tempted to rebuild your code like this.

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

0
source

Source: https://habr.com/ru/post/1338293/


All Articles