user1791841
user1791841

Reputation: 133

How to set an element's attribute with JQuery and AJAX?

I'm making a dictionary. A page contains each letter of the alphabet:

<div class="letter" id="letter-a">
<h3><a href="#">A</a></h3>
</div>
<div class="letter" id="letter-b">
<h3><a href="#">B</a></h3>
</div>

etc.

On hovering over a letter, I want a tooltip to popup with some examples of words that begin with that letter.

The examples are stored in a seperate HTML file, like so:

<div class="letter" id="letter-a">
Abdication, Absolute, Acknowledge...
</div>
<div class="letter" id="letter-b">
Bacchus, Backbite, Beard...
</div>

etc.

The quickest solution I can think of is to use a $.get call on a link's title attribute, like so:

$('.letter a').hover(function(){
  var $this=$(this);
  var letter='letter-'+$this.text();
  letter=letter.toLowerCase();
  var url='tooltip-content.html #'+letter;
  $this.attr('title', $.get($(url).text()));
}, function(){
      //etc
  });
});

But this code just displays "[object Object]" in the tooltip instead of the example words.

Does anyone know how to fix it or can suggest a more elegant solution?

Thanks in advance.

Upvotes: 2

Views: 1851

Answers (1)

Alnitak
Alnitak

Reputation: 339786

$.get returns a jqXHR object, not the text.

Try this:

$.get($url).done(function(txt) {
    $this.attr('title', txt);
});

p.s. using AJAX for each individual letter for this will be slow - it would be better to prefill the sample words directly onto the title attributes all in one go:

var letters = $.get('tooltip-content.html').done(function(html) {
     var $html = $(html);     // convert to object - don't put in the DOM
     $html.each(function() {  // iterate over each div
         var id = this.id;    // extract its ID
         $(id).attr('title', $(this).contents());
     });
});

(or something like that...)

Upvotes: 2

Related Questions