medainius
medainius

Reputation: 1

JS Function works only on one (first one) element

I am trying to accept JS plugin for all links#modal_trigger in my website, but it works only with the first one. What's wrong? I can't get to know.

My JS codes:

(function($){
    $.fn.extend({
        leanModal:function(options){
            var defaults={top:100,overlay:0.5,closeButton:null};
            var overlay=$("<div id='lean_overlay'></div>");
            $("body").append(overlay);
            options=$.extend(defaults,options);
            $(this).each(function(i){
                var o=options;
                $(this).bind('click', function(e) {
                    var modal_id=$(this).attr("href");
                    $("#lean_overlay").bind('click', function() {close_modal(modal_id)});
                    $(o.closeButton).bind('click', function() {close_modal(modal_id)});
                    var modal_height=$(modal_id).outerHeight();
                    var modal_width=$(modal_id).outerWidth();
                    $("#lean_overlay").css({"display":"block",opacity:0});
                    $("#lean_overlay").fadeTo(200,o.overlay);
                    $(modal_id).css({"display":"block","position":"fixed","opacity":0,"z-index":11000,"left":50+"%","margin-left":-(modal_width/2)+"px","top":o.top+"px"});
                    $(modal_id).fadeTo(200,1);e.preventDefault()
                })
            });
            function close_modal(modal_id){
                $("#lean_overlay").fadeOut(200);
                $(modal_id).css({"display":"none"})
            }
        }
    })
})(jQuery);

And :

<script type="text/javascript">
    $("#modal_trigger").leanModal({top : 200, overlay : 0.6, closeButton: ".modal_close" });
        $(function(){
        $(".user_login").show();
    });
</script>

Upvotes: 0

Views: 1707

Answers (1)

p e p
p e p

Reputation: 6674

The reason that's not working is because you have multiple elements in your document with the same ID. You need to be using classes instead, and using class selectors. When you have multiple elements with the same ID myId, $('#myId') will return only one element. So instead, give your elements a class class="modal_trigger" and use the selector $('.modal_trigger').

Upvotes: 1

Related Questions