Stephen Stephen - 4 months ago 29
jQuery Question

Passing independent parameter to .mouseover function

I have 32 html elements with the id names

nyg
,
nyj
, and some others. My goal is to bind a
mouseover
and
mouseout
event to each of the elements, so I can change the
color
of the box that the user is hovering over. This does not work, and I am sure there is a better way to do this while also being code efficient. I am doing this for 32 different teams, so efficiency is important. If somebody could lead me in the right direction, I would greatly appreciate it. Thanks!

HTML

<div id="content">
<ul class="conference">
<ul class="division">
<li id="nyg" class="team"></li>
<li id="nyj" class="team"></li>
<li class="team"></li>
....


JS

var teams = [
{
id: 'nyg',
name: 'Giants',
city: 'New York',
color1: '#000099',
color2: '#0000ff',
depth: 'http://www.ourlads.com/nfldepthcharts/depthchart/NYG',
offseason: 'http://espn.go.com/nfl/team/transactions/_/name/nyg',
logo: 'logos/nyg.jpeg'
},
{
id: 'nyj',
name: 'Jets',
city: 'New York',
color1: '#006600',
color2: '#009900',
depth: 'http://www.ourlads.com/nfldepthcharts/depthchart/NYG',
offseason: 'http://espn.go.com/nfl/team/transactions/_/name/nyg',
logo: 'logos/nyg.jpeg'
}];

for (team in teams) {
$('#'+teams[team].id;).mouseover( mouseIn(teams[team].color1)).mouseout( mouseOut(teams[team].color2));
}

function mouseIn(color) {
$(this).css("background-color", color);
}

function mouseOut(color) {
$(this).css("background-color", color);
}

Answer

Firstly your HTML is invalid. You cannot have a ul as a child of a ul - you need to place li between them.

To actually solve your problem you could amend your teams data to be an object, keyed by the id of the li elements, instead of an array of objects. That way you can directly access the required object on hover of the element. Try this:

var teams = {
  nyg: {
    name: 'Giants',
    city: 'New York',
    color1: '#000099',
    color2: '#0000ff',
    depth: 'http://www.ourlads.com/nfldepthcharts/depthchart/NYG',
    offseason: 'http://espn.go.com/nfl/team/transactions/_/name/nyg',
    logo: 'logos/nyg.jpeg'
  },
  nyj: {
    name: 'Jets',
    city: 'New York',
    color1: '#006600',
    color2: '#009900',
    depth: 'http://www.ourlads.com/nfldepthcharts/depthchart/NYG',
    offseason: 'http://espn.go.com/nfl/team/transactions/_/name/nyg',
    logo: 'logos/nyg.jpeg'
  }
};

$('.team').hover(function() {
  $(this).css('background-color', teams[this.id].color1);
}, function() {
  $(this).css('background-color', teams[this.id].color2);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content">
  <ul class="conference">
    <li>
      <ul class="division">
        <li id="nyg" class="team">NYG</li>
        <li id="nyj" class="team">NYJ</li>
      </ul>
    </li>
  </ul>
</div>