Danferth
Danferth

Reputation: 1879

Storing attribute values for use with jQuery

I have a set of links like so

<a class="colorBox" href="#" title="#0676B3"></a>
<a ...
<a ... these are similar links with the title containing the color value
<a ...

My goal is to use jQuery to grab the value of the title attribute and plug that into the background with .css().

My latest attempt is this:

$(document).ready(function(){
      $('a.colorBox').find().attr('title',function(){
          var color = (this);
          $('a.colorBox').css('background',color);
      });
  });

of coarse this does nothing but return an error. I'm sure it's because you cant have a callback in the .attr(). I can select the value easily but how do i store it into a variable? and how would you make the variable change to the next links title value and use that? with the .each() but how?

I am learning still so any code examples would be great or if there is an API function i am not aware about please let me know

thanks

Upvotes: 0

Views: 769

Answers (5)

digitalbath
digitalbath

Reputation: 7334

Try this:

$(function() {
    $('a.colorBox').each(function() {
        $(this).css('background-color', this.title);
    });
});

However, title is probably not the right place to stick a value like this. you'd likely be better off using a data attribute for what you're trying to accomplish, eg.

<a class="colorBox" href="#" data-bgcolor="#0676B3"></a>

and changed the javascript to something like

$(function() {
    $('a.colorBox').each(function() {
        var self = $(this);
        self.css('background-color', self.attr('data-bgcolor'));
    });
});

Upvotes: 2

ShankarSangoli
ShankarSangoli

Reputation: 69905

You should try to use the data attributes

<a class="colorBox" href="#" data-bgcolor="#0676B3"></a>

In the js you can use jQuery data method to retrieve the value

$(function() {
    $('a.colorBox').each(function() {
        $(this).css('background-color', $(this).data('bgcolor'));
    });
}); 

Upvotes: 0

marc
marc

Reputation: 6223

Try

$(function() {
    $('a.colorBox').each(function() {
        $(this).css('background-color', $(this).attr('title'));
    });
});

Upvotes: 0

Shef
Shef

Reputation: 45589

$(document).ready(function(){
    $('a.colorBox').each(function(){
      var $this = $(this);
      $this.css('background-color', $this.attr('title'));
    });
});

Upvotes: 3

Paul
Paul

Reputation: 141839

$(document).ready(function(){
  $('a.colorBox').each(function(){
    $(this).css('background-color', $(this).attr('title'));
  });
});

Upvotes: 0

Related Questions