4

HTML :

<div id="tab">This is a paragraph.</div>
<div id="tab">This is a paragraph.</div>
<div id="tab">This is a paragraph.</div>
<div id="tab">This is a paragraph.</div>

CSS :

#tab{
  height:30px;
  width:130px;
  background-color:red;
}

Jquery :

$(document).ready(function() {
    function randomNumber() {
        return Math.floor(Math.random() * 255)
    }
    $('#tab').mouseover(function() {
        $('#tab').css('background-color', 'rgb(' + randomNumber() + ',' + randomNumber() + ',' + randomNumber() + ')');
    });
    $('#tab').mouseout(function() {
        $('#tab').css('background-color', 'white');
    });
});

I have this fiddle and I want the color change to affect ALL the #tabs, not just the first one, how do i do it?

Fiddle example can be found here.

3
  • 2
    the id are unique, change to class Commented Sep 20, 2012 at 9:11
  • 2
    you need to set same class for this..ids must be unique in a page Commented Sep 20, 2012 at 9:11
  • 1
    Can't, because #tabs equals an id (#). and an ID can only be assigned to 1 element, one time. you need to use an class (.), that will work Commented Sep 20, 2012 at 9:11

5 Answers 5

2

You can only assign an ID once! Change it to classes like this http://jsfiddle.net/nHCXV/3/

Sign up to request clarification or add additional context in comments.

1 Comment

perfect, exactly what i was after :)
1

Use a class instead. then you can access them all using

 $('.classname')

Comments

1

You need to change the id attribute as class because the id is unique. Let try this is in jsfiddle

Comments

1

Here is an fiddle witch the right way:

http://jsfiddle.net/ToBadForU/9p7ud/

This is what you want, right?

2 Comments

I think he wants on every elements
@CharlesJourdan, you're right, but i didn't save it right... I've updated the link
0

Instead of giving same id's you can declare the div's without any id's or class and give the code below. To know more about selectors go to this link.

$(document).ready(function() {
function randomNumber() {
    return Math.floor(Math.random() * 255)
}
$('div').mouseover(function() {
    $('div').css('background-color', 'rgb(' + randomNumber() + ',' + randomNumber() + ',' + randomNumber() + ')');
});
$('div').mouseout(function() {
    $('div').css('background-color', 'white');
  });
});​

or else simply use class instead of id's. Because id's are unique but not classes.

2 Comments

This would affect all other div's too so assigning classes would be the best choice.
It can be achieved by using jquery selectors. I updated my answer :)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.