Rolando
Rolando

Reputation: 62704

How to highlight clicked div?

I have a series of divs like this:

<div id="listofstuff">
    <div id="anitem">
        <span class="itemname">Item1</h3></span>
        <span class="itemdescruption">AboutItem1</span>
    </div>
    <div id="anitem">
        <span class="itemname">Item2</h3></span>
        <span class="itemdescruption">AboutItem2</span>
    </div>
    <div id="anitem">
        <span class="itemname">Item3</h3></span>
        <span class="itemdescruption">AboutItem3</span>
    </div>
</div>

I want to make to so when the user clicks on an "anitem", the one that was clicked is highlighted and the itemname only pops up in an alertbox.

Upvotes: 3

Views: 4089

Answers (2)

dknaack
dknaack

Reputation: 60556

Description

At first i have to say that id's must be unique in your document, choose a class instead. Then you can use jQuerys click() and css() method to change something.

The id attribute specifies a unique id for an HTML element (the id attribute value must be unique within the HTML document).

Check out my sample and jsFiddle Demonstration

Sample

<div id="listofstuff">
<div class="anitem">
       <span class="itemname">Item1</h3></span>
       <span class="itemdescruption">AboutItem1</span>
</div>
<div class="anitem">
       <span class="itemname">Item2</h3></span>
       <span class="itemdescruption">AboutItem2</span>
</div>
<div class="anitem">
       <span class="itemname">Item3</h3></span>
       <span class="itemdescruption">AboutItem3</span>
</div>
</div>


$(".anitem").click(function() {
   $(this).css("backgroundColor", "red"); 
});

More Information

Upvotes: 4

BartekR
BartekR

Reputation: 3977

First - you have multiple id parameters with the same value - it's wrong.ID must be unique. I've changed it to class. So instead of <div id="anitem"> there is <div class="anitem">

$(function() {
    $('.anitem').click(function() {
        $(this).css('background-color', '#d00');
        alert($(this).find('.itemname').html());
    })
})

Upvotes: 2

Related Questions