简体   繁体   中英

jquery event for on render an element

I am trying to do all dom manipulations off screen and then make it visible. Which works, except now I have the situation where I am trying to do it with a form which I want to focus on the first input text upon rendering it on the browser.

Something like: myForm.prependTo(myDiv).show().find('input:first').focus();

Problem is that the focus is being called before the form has finished rendering which is causing the lovely error 'Can't move focus to the control because it is invisible, not enabled, or of a type that does not accept the focus'

How do other web developers handle the similiar situation of manipulating elements off screen and then making it visible? I wish jQuery had something like
myForm.prependTo(myDiv, function() { /* on render code here */ })

I know one way of doing it is setting a timeout and when it fires I put focus on the input, but I feel like that's not really the cleanest way to do things. I know the iframe has an onload event, so I'm curious if people usually draw their elements in some hidden iframe and listen for its load event to know when the element has finished rendering? If so could you point me to an example of doing this?

myForm.prependTo(myDiv).show(function(e){
    $(this).find('input:first').focus();
});​

I know I'm 7 years late, but I had a similar problem, which I solved by putting the stuff I needed to happen after the render in a ready handler.

I had a restore function that worked, but there was zero or near zero visual feedback that the element had been restored.

I tried emptying the element first. It still worked, but still had zero visual feedback.

$("#someSelector").empty(); restore();

Then I discovered ready() happens after the rendering; so I changed it to something like....

$("#someSelector").empty().ready(function() { restore(); });

Now the restore() doesn't happen until after the empty() action RENDERS. This means my element APPEARS to empty out and then refill (it always did, but now the user can see it happen).

I found this solution somehow a few days ago for a different problem with some vague search that I can't remember. Then I needed it again but couldn't exactly remember what I did. Now my searches included the word "jquery" and "render" and lead me here.

I ended up going thru my code to find out what I did, and I thought it might be a good idea to post it here in case other people stumble on this post and actually need to execute something AFTER rendering happens.

Cheers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM