1

I am trying to figure out how to use jquery to take an image with a class of active, to take the "rel" data and apply that text to text inside another div with a h2 tag. I am very new to jQuery and still trying to wrap my mind around it. Please explain what is happenning a bit, so it makes sense! Thank you ahead of time for the answers!

All I can figure out is this:

jQuery (I know I'll need this... just not sure how to apply it)

var title = $("#slider img.active").attr("rel");

The HTML:

<div id="slider">
    <div id="sliderimgholder">
        <img class="active" src="images/slider-1.jpg" alt="" rel="image one" />
        <img class="" src="images/slider-2.jpg" alt="" rel="image two" />
        <img class="" src="images/slider-3.jpg" alt="" rel="image three" />
    </div>

    <div id="ribbon">
        <h2>THIS SHOULD BE POPULATED WITH text image one</h2>
    </div>
</div>
1
  • Did any of the posted answers work for you, or are you having further problems..? Feb 20, 2012 at 22:27

3 Answers 3

0

Check out the text function:

var title = $("#slider img.active").attr("rel");

$("#ribbon h2").text(title);

Example: http://jsfiddle.net/eYPW4/

0

You can use the text method to set the text content of an element. You just need to select the right element, which you can do with a simple selector:

$("#ribbon h2").text(title);

However, it's important to note that this would place the text in every h2 element that is a descendant of #ribbon. In the example in your question, that won't be a problem as there is only one, but it's worth remembering in case that changes.

Also note that if you want to store arbitrary data on an element, you can use the HTML5 data-* attributes, so you don't need to find other attributes like rel.

2
  • How difficult would this be to expand it to use with a image fader.. so the images inside sliderimgholder fade in and out and update the h2 in ribbon?
    – amazedinc
    Feb 20, 2012 at 0:22
  • @user1204678 - Not difficult. Look at the fadeIn and fadeOut methods in the jQuery documentation. Feb 20, 2012 at 6:56
0

I'd suggest:

$('#sliderimgholder img').click(
    function(){
        $('#ribbon h2').text($(this).attr('rel'));
    });

JS Fiddle demo.

Amended slightly, to avoid creating a jQuery object inside the text() method:

$('#sliderimgholder img').click(
    function(){
        $('#ribbon h2').text(this.getAttribute('rel'));
    });

JS Fiddle demo.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.