Alon
Alon

Reputation: 7758

How to bind same action for 2 elements

I have a basic code like this (that duplicates several times):

<h3 class="header">The header</h3>
<div class="content"> The content 
    <div class="showUp">hidden text</div>
</div>
<h3 class="header">The header2</h3>
<div class="content"> The content 2
    <div class="showUp">hidden text 2</div>
</div>

I want to create a roll over event that if I hover on the h3 or the div.content the .showup class will be shown. I only managed to create a rule for if I roll over the div.content class:

$('.content').mouseenter(function() {
    $(this).find(".showUp").animate({left: 0},300)
})
.mouseleave(function() {
    $(this).find(".showUp").animate({
        left: -200
    }, 500);
}); 

I know I can create an event for the header like this:

$('h3').mouseenter(function() {
    $(this)**.next()**.find(".showUp")...
});

but how do I bind these to elements to do the same thing using the the word "this" to one function

Upvotes: 3

Views: 191

Answers (3)

Alon
Alon

Reputation: 7758

this example somehow didn't work (perhaps I did something wrong) but I found out that instead of writing this:

.add($(this).find('+ content > .showUp'))

I wrote this and it workded for me:

.add($(this).next().find('.showUp')

Upvotes: 0

Alessandro Vendruscolo
Alessandro Vendruscolo

Reputation: 14875

This should do the trick.

$('.content, h3')
    .mouseenter(function() {
        $(this).find('+ .content > .showUp').add($(this).find('> .showUp')).stop().animate({left: 0},300)});
    })
    .mouseleave(function() {
        $(this).find('+ .content > .showUp').add($(this).find('> .showUp')).stop().animate({left: -200},500)});
    });

We attach an event listener to both the .content and the h3. Then in the event listener we search for an immediate sibling if it exists (+ .content > .showUp) or an immediate child (> .showUp) if it exists.

So, in any case we'll get the .showUp div to animate.

I've also added the .stop() method to stop the animation before animating it (so it won't have some quirk behavior if you hover the h3 and then the .content.

I've made here a basic fiddle here, so you can see how it works.

Upvotes: 5

Pritom
Pritom

Reputation: 1333

make a function such "allMouseEnter" and call it from both $('.content').mouseenter and $(h3).ouseenter function. Maybe it helps you, But I am not sure. Only you can try with this.

Upvotes: 0

Related Questions