Set z-index with javascript setTimeout ()

What I'm trying to do is to have 4 extensible divs overlapping each other with the transition set to css for 0.6s. Since the extension lasts up to 0.6 s, I would like the extended div to lose its higher z index after it is collapsed, otherwise it looks silly. However, this does not work, the z-index remains unchanged. This is probably stupid, but I just can't find it. Thanks!

<div class="wrapper" style="position: relative;"> <div id="one" style="position: absolute;" onmouseover=" this.style.height='250px'; this.style.zIndex='1'; " onmouseout=" this.style.height='50px'; setTimeout(function() {this.style.zIndex='0';},600); ">blahblahblahblah</div> <div id="two" style="position: absolute;" onmouseover=" this.style.height='250px'; this.style.zIndex='1'; " onmouseout=" this.style.height='50px'; setTimeout(function() {this.style.zIndex='0';},600); ">blahblahblahblah</div> </div> 
+4
source share
1 answer

Instead of finding an error in your code, it might be useful to discuss how you could find it yourself. The first step is to open the devtools window (F12) and open the console (click on the small icon that looks like a sign bigger than a sign with three horizontal stripes on the right). When you run your program, you will probably see the following:

 TypeError: Cannot set property 'zIndex' of undefined 

The debugger will stop at a line

 setTimeout(function() {this.style.zIndex='0';},600); 

Hmmm. Apparently this.style undefined. How could this be? Go to the console (which is in the context in which the error occurred, in other words, inside the function you passed setTimeout) and type

 this.style 

and you will see that it is undefined. Why is this? Well, what is this ?

 this 

and you will see something like

 Window {top: Window, window: Window, location: Location, ...} 

Why would this be a window instead of what I think it should be? Well, this usually set to window for a function called without explicit this , as in elt.set_style() . What's going on here.

How can I set this inside a function called by the system, for example, the one that was passed to setTimeout ? You can do what @Satpal recommended, and save the value of this outside the function under a different name, such as self , and explicitly reference it. Or you can bind a function to this , as in

 function timeout_func(){ this.style.zIndex=0; } setTimeout(timeout_func.bind(this)); 

In addition to using the console to see error messages and enter things that need to be evaluated, you will find very useful Variable Regions and Watch Expressions windows.

In general, such problems can be easily solved with devtools. If you do not know what it is, Google Chrome devtools (start by pressing F12). Do not use it literally, like programming in the dark.

+5
source

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


All Articles