Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Focus to a link using class name with Jquery

Tags:

html

jquery

css

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.

like image 420
VikingGoat Avatar asked Mar 04 '10 16:03

VikingGoat


Video Answer


2 Answers

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();
});
like image 161
Nick Craver Avatar answered Oct 13 '22 13:10

Nick Craver


Maybe use

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

rather than

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

like image 25
Randall Avatar answered Oct 13 '22 13:10

Randall