jonullberg
jonullberg

Reputation: 27

How to append content from one element to another on hover event

So I have four links with titles that I want to get the attribute values from and append to an external, empty div.

Here is the jsFiddle

The part I'm having problems with is the javascript

$('li a.link').hover(
    function(){
        $(this).text().appendTo('.container');
    });

I don't care if I grab the attribute value or the text inside, but neither seems to work. I've gotten the empty div to say "Hello World!" when I hover over the links, but I can't get it to grab either the Title value or the text within the HTML and any help is appreciated.

Upvotes: 0

Views: 189

Answers (4)

Daniel Jordan
Daniel Jordan

Reputation: 286

I presume that if this is a hover even you'd also want the text to disappear on mouseleave of the "Li a" so I made you a jsFiddle example to do both. Please check it out and if any questions feel free to ask.

$(document).on('mouseenter','li a',function(){
    $('.container').text($(this).attr('title'));
}).on('mouseleave','li a', function(){
    $('.container').text('');
});

http://jsfiddle.net/danieljordan13/JfGhY/11/

Upvotes: 1

jtheman
jtheman

Reputation: 7491

I prefer using append() before appendTo()

This works:

$('.container').append($(this).text());

See http://jsfiddle.net/JfGhY/5/

To append the title:

$('.container').append($(this).attr('title'));

http://jsfiddle.net/JfGhY/10/

Upvotes: 0

David Thomas
David Thomas

Reputation: 253396

I'd suggest, if you want to append the text:

$('li a').hover(
    function(){
        var text = $(this).text();
        $('.container').text(function(i,t){
            return t + ' ' + text;
        });
    });

JS Fiddle demo.

Or, if you want to replace the text:

$('li a').hover(
    function(){
        var text = $(this).text();
        $('.container').text(text);
    });

JS Fiddle demo.

Having re-read the question, and seen you want to use the title attributes, I'd suggest, instead:

$('li a').hover(
    function(){
        var title = this.title;
        $('.container').text(title);
    });

JS Fiddle demo.

References:

Upvotes: 0

Adil Shaikh
Adil Shaikh

Reputation: 44740

$('li a.link').hover(function(){
        var title = $(this).attr('title');
        $('.container').append(title);
});

Fiddle

Upvotes: 0

Related Questions