Kiren S
Kiren S

Reputation: 3097

Issue with scrollIntoView and focus

var mediaIdForFocus = '<?php echo $this->mediaIdForFocus; ?>';
if(mediaIdForFocus)
$('#flagimg'+mediaIdForFocus).get(0).scrollIntoView().addClass("selectedMedia"); // highlight class
$('.logoTxt').focus();

I am trying to adjust the scroll of a div $('#flagimg'+mediaIdForFocus) then give the focus to the element $('.logoTxt')

Scroll view is adjusted to the element $('#flagimg'+mediaIdForFocus) but, $('.logoTxt').focus(); is not giving the focus. It happens only on first time. If I refresh the page it is working as expected.

Please help me.

Upvotes: 8

Views: 11571

Answers (3)

Miguel Carvajal
Miguel Carvajal

Reputation: 1964

To smoothly scroll an element into view and set the focus to it you can do something like

elm.scrollIntoView({behavior: 'smooth', block: 'center'});
elm.focus({preventScroll: true});

Upvotes: 29

Jacob van Lingen
Jacob van Lingen

Reputation: 9537

The problem is propably the codeline $('#flagimg'+mediaIdForFocus).get(0).scrollIntoView().addClass("selectedMedia");

The .get(0) returns the plain element, so the jQuery wrapper is gone. .addClass() is a jQuery function, executing jQuery functions at plain elements is not possible.

So first add the class and afterwards scroll the element in your view: $('#flagimg'+mediaIdForFocus).addClass("selectedMedia").get(0).scrollIntoView();

Upvotes: 0

Kiren S
Kiren S

Reputation: 3097

$(document).scrollTop(0); did the trick

Code is given below

// for setting the focus to selected media if it is chosen from media page.
var mediaIdForFocus = '<?php echo $this->mediaIdForFocus; ?>';
if(mediaIdForFocus)
   $('#flagimg'+mediaIdForFocus).get(0).scrollIntoView(); // highlight class
$(document).scrollTop(0);

Upvotes: 0

Related Questions