Question

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.

Was it helpful?

Solution

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)

OTHER TIPS

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

jQuery('.commonClass');

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();
    });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top