0

I am trying to better understand scope and chaining in javascript. I have the following which works just fine

$("div.sked, div.report, div.database").hover (function (){
     let $this = $(this);
     let $pos = $this.position();
     $submenu = $this.find (":first-child");
     $submenu.css ('left', $pos.left + 30);
     $submenu.css ('top', $top);
     $submenu.show();
     })
     .mouseleave  (function (){
     $submenu.hide();
 });

But when I add a let before $submenu = $this.find (":first-child"); Then $submenu goes out of scope and submenus are not hidden.

I would like top understand the proper way to code this.

Thank you...

1 Answer 1

1

That's because let variables are block scoped, and not are function scoped. If you declare the variable in the first callback, you cannot use it in the other callback because the block has been changed.

To share a variable among the two functions, you will need to declare it at a place which makes it available to both of the scopes.

But, in your case, there is no such place as event handlers can be executed irrespective of their declared order. So, you will need to fetch the element again in the mouseleave's callback.

$("div.sked, div.report, div.database").hover(function() {
    let $this = $(this);
    let $pos = $this.position();
    $submenu = $this.find(":first-child");
    $submenu.css('left', $pos.left + 30);
    $submenu.css('top', $top);
    $submenu.show();
  })
  .mouseleave(function() {
    let $this = $(this);
    $submenu = $this.find(":first-child");
    $submenu.hide();
  });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.