views:

121

answers:

3

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.

+2  A: 

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

jQuery('.commonClass');

RibaldEddie
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
I could be wrong - I am not sure what exactly your solution means.
Ankur
You can access the element that triggered the event inside your handler function, and then display the correct div for that element.
RibaldEddie
+3  A: 

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
But I want to be able to access each individually
Ankur
ok will try it now
Ankur
+1  A: 

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