mike
mike

Reputation: 749

if same class, fadeIn / fadout

I have a setup here in jsFiddle: http://jsfiddle.net/2PmnQ/

I'm trying to make a function that will check if the modal has the same class as the button so the button will bring up the modal with the same class. I'm obviously trying to do this dynamically all within one function rather than doing a if statement for every class.

var p = $(".popUp");
var position = p.position();
var tagLength = $("p a").width();
$( ".modal" ).css({left: (position.left + tagLength + 10) + "px", top: position.top + "px"});

$( ".popUp").hover(

    function() {
      $( ".modal" ).stop().fadeIn();
    }, function() {
      $( ".modal" ).stop().fadeOut();
    }

);

Upvotes: 0

Views: 88

Answers (1)

Andy
Andy

Reputation: 30135

I would use a custom data attribute instead of a class to save the target class:

<p class="popUp" data-modal="one"><a>popUp one here</a></p>
<p class="popUp" data-modal="two"><a>popUp two here</a></p>

<div class="modal one">PopUp one should be here</div>
<div class="modal two">PopUp two should be here</div>

That way you don't have to filter the target out of the trigger element classes and only need this in your hover function:

$('.popUp').hover(function(){    
    $('.modal.'+$(this).data('modal')).fadeIn();
},function(){
    $('.modal.'+$(this).data('modal')).fadeOut();
});

http://jsfiddle.net/2PmnQ/1/


V2 using jQuery UI position() plugin:

<!-- i switched the popup classes to the `a` here so it works in the fiddle -->
<p><a class="popUp" data-modal="one">popUp one here</a></p>
<p><a class="popUp" data-modal="two">popUp two here</a></p>

<div class="modal one">PopUp one should be here</div>
<div class="modal two">PopUp two should be here</div>

JS:

$('.popUp').hover(function(){    
    $('.modal.'+$(this).data('modal'))
        // reset positions otherwise it doesn't work correctly after the first time. don't know why :(
        // looks like this problem: http://forum.jquery.com/topic/position-keeps-adding-original-left-and-top-to-current-values-in-ie-8
        .css({'left':0,'top':0}) 
        // position modal 10px to the right of the popup link    
        .position({'my':'left+10 center', 
                   'at' : 'right center', 
                   'of' : $(this)
                  }
    ).fadeIn();
},function(){
    $('.modal.'+$(this).data('modal')).fadeOut();
});

http://jsfiddle.net/2PmnQ/10/

(Be sure to include the jQuery UI with at least the position plugin: http://jqueryui.com/download/#!version=1.11.0&components=0001000000000000000000000000000000000. Yeah maybe it's a bit overkill for this but it's really convenient)

Upvotes: 3

Related Questions