Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move focus to page element [duplicate]

Possible Duplicate:
Move focus to a particular field

This should be an easy one. I'm trying to set the focus onclick to a <p> element on my page.

My javascript looks like this:

function loadSubmit() {
    if (document.getElementById('uploaded_file').value == "") {
        this.setFocus("name");
    } else {
        var ProgressImage = document.getElementById('progress_image');
        document.getElementById("progress").style.visibility = "visible";
      //document.getElementById("progress").focus(); ?
        setTimeout(function () {
            ProgressImage.src = ProgressImage.src
        }, 100);
    }
}

I would like to shift the focus of the page to 'progress_image' any suggestions on how to accomplish this?

Thanks

like image 901
Kinburn101 Avatar asked Feb 03 '26 22:02

Kinburn101


2 Answers

Thanks @rlemon for pointing me in the right direction. For those who come across this post seeking the same answer as me; my solution was as follows.

If you need to set focus to an element on your page using an onclick event you can do so by defining your element with tabindex and an ID.

For example I have:

<div id="whatever">sometext or whatever</div> 

and I would like the to focus on that div with a submit button or the like. We already know this can be accomplished for input fields by using as other posters had suggested:

document.getElementById("whatever").focus();

With a simple change to your div like this:

<div id="whatever" tabindex="-1">sometext or whatever</div>

your div will come into the page's focus with your onclick event. Now knowing this, it is as simple as positioning an empty div, or anchor, or whatever onto your page to achieve your desired results to set the proper focus.

I hope this helps others and thanks again to other posters helping me out with this including: http://snook.ca/archives/accessibility_and_usability/elements_focusable_with_tabindex/

like image 70
Kinburn101 Avatar answered Feb 06 '26 10:02

Kinburn101


You can see more about the focus function here: https://developer.mozilla.org/en-US/docs/DOM/element.focus

document.getElementById('fieldId').focus();
like image 25
Chase Avatar answered Feb 06 '26 12:02

Chase