6

Using jQuery I am trying to set focus for (CSS purposes) to a particular link from a list of related links on the load of the page based upon the class name.

Example, of the following I want to set focus to Link1

<a href="#Link1" class="nav-button-left">Link1</a>
<a href="#Link2" class="nav-button">Link2</a>
<a href="#Link3" class="nav-button">Link3</a>
<a href="#Link4" class="nav-button">Link4</a>
<a href="#Link5" class="nav-button">Link5</a>
<a href="#Link6" class="nav-button-right">Link6</a>

Currently this is the code snippet I have working so far, and by working I mean I've set it up, it does nothing noticeable so far.

<script type="text/JavaScript">
    $(window).load(function(){
        if($(this).attr("class") == 'nav-button-left'){$(".nav-button-left").focus();}  
    })
</script>

I'm fairly sure its the actual focus portion that's not working, although I can't fathom.

1
  • 1
    I suspect $(this) doesn't contain what you think it does. Also, jQuery includes a .hasClass() function, which might suit your needs better. Commented Mar 4, 2010 at 16:39

2 Answers 2

13

You can just call .focus(), you don't need the if:

$(".nav-button-left").focus();

In this code: if($(this).attr("class") == 'nav-button-left'){ the reference this has the window context, so it's evaluating false since the window doesn't have that class.

If what you're trying to do is only call it if the element exists, you're set. In the above code, if the element isn't found then .focus() just won't be called since the selector didn't find anything.

Also, unless you need stuff to load like images before this executes, just use this call:

$(function() { //equivalent to document.ready
  $(".nav-button-left").focus();
});
Sign up to request clarification or add additional context in comments.

Comments

2

Maybe use

$(this).hasClass(".nav-button-left")

rather than

$(this).attr("class") == 'nav-button-left'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.