0

Not an expert, so I am trying to understand why this condition fails. I want it to set focus on .alert-focus if the css classes are present in the page, otherwise if they are not it should set focus on #maincontent. However it never ends up setting focus on #maincontent.

here is my code:

$(function() {
    if ($('body .alert, body .success, body .warning').length) {
        $('.alert-focus').focus();
    } else  {
        $('#maincontent').focus();
    }
});

<a id="maincontent" tabindex="-1" name="maincontent"></a> 
zemaker
  • 171
  • 1
  • 11

1 Answers1

0

Your code does work as long as there is some content inside the <a> element to show.

The example below shows this by adding a CSS rule that only applies to maincontent when it has the focus.

$(function() {
    if ($('body .alert, body .success, body .warning').length) {
        $('.alert-focus').focus();
    } else  {
        $('#maincontent').focus();
    }
});
/* If you see a yellow background, the element has the focus! */
#maincontent:focus { background-color:yellow; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<!-- If an element doesn't have any content, then there's nothing to see.
     You have to give the element something to be marked up. -->
<a id="maincontent" tabindex="-1" name="maincontent">test</a>
Scott Marcus
  • 57,085
  • 6
  • 34
  • 54