bourax bourax - 1 year ago 67
Javascript Question

Object reference passed in function argument

I want to change the color of link with jQuery. I get an error when I try to reference to the object.

my HTML :

<a onmouseover="loclink(this);return false;" href="locations.html" title="Locations" class="nav-link align_nav">Locations</a>


My JS:

function loclink(a){
a.css("color", "red"); // Didn't work
jQuery('a').find('.nav-link').css("color", "red"); // Didn't work
$(a).find('.nav-link').css("color", "red"); // Didn't work

console.log(a):

<a onmouseover="loclink(this);return false;" href="locations.html" title="Locations" class="nav-link align_nav">Locations</a>

Answer Source

function loclink(a){
    $(a).css("color", "red"); // this should work
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a onmouseover="loclink(this);return false;" href="locations.html" title="Locations" class="nav-link align_nav">Locations</a>

A better approach (instead of using inline events) is to use Jquery.on to attach an event handler to your links

$("a.nav-link").on("mouseover",function (){
    $(this).css("color", "red"); // this should work
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a  href="locations.html" title="Locations" class="nav-link align_nav">Locations</a>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download