1

I have about 6 div elements with the same class. When I mouseover any one of them I want to show a nother div next to them.

I am thinking of giving them all an id of the form id="mydiv-divname" where mydiv- will always be constant.

How would I reference the mydiv-* elements. I can't find the exact syntax but I think it should be something like $("#mydiv-"[*]) where the * represents some kind of wildcard.

Ankur
  • 50,282
  • 110
  • 242
  • 312

3 Answers3

3

What purpose does the ID serve? If they are all tagged with the same class name, you can access them all by class:

`$(".className")...

To trigger an event when one of those elements is hovered, use

`$(".className").hover(... )

Note that the function within the hover() will only be triggered for the element which is actually being hovered.

They do something similar to what you're trying to achieve here - fading one element in or out on hover (of many elements on the page marked with that class)

Dexter
  • 18,213
  • 4
  • 44
  • 54
2

Why can't you just use the class in the selector instead of the id, as in

jQuery('.commonClass');

RibaldEddie
  • 5,136
  • 2
  • 23
  • 22
  • Then when I mouseover one of the items with the class="commonClass", all the items with that class end up having the new div show up to the right hand side. – Ankur Nov 27 '09 at 06:07
  • I could be wrong - I am not sure what exactly your solution means. – Ankur Nov 27 '09 at 06:08
  • You can access the element that triggered the event inside your handler function, and then display the correct div for that element. – RibaldEddie Nov 27 '09 at 06:10
2

It seems you are going for something like this:

HTML:

<div class="content" id="con_a">Hello world.</div>
  <div id="show_con_a" style="display:none">Show Me on content div "a" hover</div>

<div class="content" id="con_b">Nice to meet you.</div>
  <div id="show_con_b" style="display:none">Show Me on content div "b" hover</div>

<div class="content" id="con_c">See you later.</div>
  <div id="show_con_c" style="display:none">Show Me content div "c" hover</div>

JAVASCRIPT:

//Collect all divs with 'content' class
$('.content').each(function(){
    //Set mouse handler for each content div
    $(this).hover(function(){
        $('#show_' + this.id).show();
    },
    function(){
        $('#show_' + this.id).hide();
    });
});

ALTERNATIVE JAVASCRIPT:

//Collect all divs with an id that begins with 'con_'
$("[id=^'con_']").each(function(){
    //Set mouse handler for each content div
    $(this).hover(function(){
        $('#show_' + this.id).show();
    },
    function(){
        $('#show_' + this.id).hide();
    });
});
micahwittman
  • 12,356
  • 2
  • 32
  • 37