Jack
Jack

Reputation: 33

jQuery: Get ids from class

I have a lot of div's and I want to fade this one who is hovered.
How i can get the id of the hovered div?
Is there anyway to do that except calling function(and sendind the id) with "onmouseover"?
Thanks!

Upvotes: 3

Views: 29598

Answers (3)

ShivarajRH
ShivarajRH

Reputation: 940

On hover on these div's...

HTML:

<div class="add_post_cmmnt" id="box-100" >Box1</div>
<div class="add_post_cmmnt" id="box-200" >Box2</div>
<div class="add_post_cmmnt" id="box-400" >Box3</div>

JavaScript:

 $(".add_post_cmmnt").hover(function(e) {

      var id = this.id; // Get the id of this

      console.log("id is " + id); //Test output on console 

      $('#pid').val(id); // Set this value to any of input text box

      $(this).fadeOut(400); // Finally Fadeout this div

});

Upvotes: 2

Mariano Cavallo
Mariano Cavallo

Reputation: 959

You could set a class to flag the divs after you applied the animation so you can easily identify hovered divs.

(function($){
    $.fn.extend({ 
        myDivHover: function(){
            var $set = $(this);
            return $set.each(function(){
                var $el = $(this);
                $el.hover(function(){
                    fadeOutAnimation( $el, $set );
                }, function(){
                    fadeInAnimation( $el );
                });

            });
        }
    });

    function fadeOutAnimation( $target, $set ){

        // Revert any other faded elements
        fadeInAnimation( $set.filter('.hovered') );

        // Your fade code here
        ...
        ...

        // Flag
        $target.addClass('hovered');
    }

    function fadeInAnimation( $target ){

        // You revert fade code here
        ...
        ...

        // Unflag 
        $target.removeClass('hovered');
    }

})(jQuery);

// Apply it to the divs with XXX class
$('div.XXX').myDivHover();

// Select hovered item
var theID = $('div.XXX').filter('.hovered').attr('id');

Hope it helps :)

Upvotes: 0

ThoKra
ThoKra

Reputation: 3029

try something like

$(".classes").mouseover(function() {
    $(this).function();
};

to get the ID of an element you use the attr function

$('.name').attr('id');

Upvotes: 14

Related Questions