Page 1 of 1

Bold clicked element, unbold the rest

Posted: Wed Aug 04, 2010 8:36 pm
by Trahb
Well, basically what I want to do is have a list of information. When the user clicks one thing, it goes bold. When they click another, it goes bold and the other goes back to normal.

The problem is, I've tried at least 10 different ways of this and none work.. Any ideas?

Right now i'm using

Code: Select all

onclick="document.getElementById('name').className='normal'; this.className='bold';"
But, since there are multiple elements with the id "name" it only takes the first one. How can i fix this? I feel like it's really simple (guarantee it is) i just can't figure it out..

Re: Bold clicked element, unbold the rest

Posted: Wed Aug 04, 2010 9:00 pm
by superdezign
An ID is supposed to be unique. Having more than one element with the same ID is improper markup and JavaScript is acting on the DOM as it should.

Re: Bold clicked element, unbold the rest

Posted: Wed Aug 04, 2010 9:56 pm
by Trahb
I understand that, but would it really be ethical to have the same number of ids as there are entries for that particular user, and go through a loop of every number up to that amount each time they click a new entry? I feel like that's a waste, but, it may have to be what I do..

Re: Bold clicked element, unbold the rest

Posted: Thu Aug 05, 2010 2:17 am
by superdezign
Ethical? Every record in a database has a unique ID. What's different about elements on your page?
One way to do this is to place all of the elements into an array and, upon clicking one, change them all.

Code: Select all

<ul>
  <li id="item-1" onclick="toggle('item-1')">Item #1</li>
  <li id="item-2" onclick="toggle('item-2')">Item #2</li>
  <li id="item-3" onclick="toggle('item-3')">Item #3</li>
</ul>

Code: Select all

var elements = ['item-1', 'item-2', 'item-3'];
function toggle(id) {
  for (var i in elements) document.getElementById(i).className = 'normal';
  document.getElementById(id).className = 'bold';
}