Jquery onblur event and scrollIntoView

HI folks,
in below coding, 1 works, 2 does not.
but in 2 alert works. why not scroll works?

//1. button click
$("#btn_last").click(function(){   

     $("#section15")[0].scrollIntoView({
        behavior: "smooth", // or "auto" or "instant"
        block: "center", //"end" or "end"         
        inline: "center"
    });   
    
});

//2. text box blur
$("#age").blur(function(){
     $("#section15")[0].scrollIntoView({
        behavior: "smooth", // or "auto" or "instant"
        block: "center", //"end" or "end"         
        inline: "center"
    });
    alert('done');

});

Are there any errors in your browser’s console?

1 Like

I was intrigued so put up a codepen :slight_smile:

There are no errors shown but the function doesn’t get called when blurred on the input but fine with a click on the button.

I managed to get the following version working using focusout and vanilla js but perhaps you can explain why one works and the other one doesn’t :slight_smile:

2 Likes

Yes, that is an interesting oddity that you’ve found there. Others have found the same problem with scrollIntoView.

After some minor testing, I’ve found that the scroll works when you wrap the function code in a setTimeout call.

$("#age").on("blur", function () {
  setTimeout(function () {
    $("#section15")[0].scrollIntoView({
      behavior: "smooth", // or "auto" or "instant"
      block: "center", //"end" or "end"
      inline: "center"
    });
    console.log("done");
  }, 0);
});
2 Likes

nop no errors are shown at all.

Thanks i will try this now.

I should clarify this situation. The blur event and the function for that blur event does get called. The problem is that scrollIntoView doesn’t seem to have any effect during the blur event.

That problem is resolved by waiting until the blur event is finished, by using setTimeout as shown above.

2 Likes

Yes undetood.

i think we can close this case now. Thanks to all, Special Thanks Paul_Wilkins too for the fix.

  • i think in firefox i just noticed in blur > scrollIntoView seems works. but not in chrome.
    but paul’s fix works in all browsers. cheers !!
2 Likes

For what it’s worth, my mind ran along similar tracks to Paul;
blur dispatches at a slightly different time as focusout (Focusout fires before the element loses focus, blur is dispatched after.
I suspect the browser is suffering a conflict between trying to scroll to the element as prescribed by the javascript and it’s own internal handling of blur/focus positioning (trying to bring the new focus element to view), which is why both focusout (because it resolved the move before executing the browser’s positioning) and setTimeout(because it allowed the browser’s positioning to resolve, and then execute the scroll) worked.

Interesting little foible.

4 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.