I want the fancybox to close when either of the spans are clicked, currently it seems to be reopening the window after they are clicked and clicking anywhere else closes it like it should.
<div class="fancybox" style="display: none;">
<span class="ChooseEnglish">English</span>
<span class="ChooseCymraeg">Cymraeg</span>
</div>
$(".fancybox").fancybox({
closeClick: true
});
$( ".fancybox" ).trigger( "click" );
$( ".ChooseEnglish" ).click(function() {
$.fancybox.close();
});
$( ".ChooseCymraeg" ).click(function() {
$.fancybox.close();
});
Thanks
Alex
The issue is that the selector .fancybox
is bound to fancybox but it's also the content of fancybox. In other words, that selector is both the trigger and the target of fancybox.
Of course, any click
on the selector and/or its contents (your <span>
) will trigger fancybox over an over again.
You need another selector to fire fancybox (that can be hidden if you prefer so) like :
<a href="#fancybox" class="fancybox" style="display: none;"><a>
Then change the div
selector from class to ID so it can be targeted by the link like :
<div id="fancybox" style="display: none;">
<span class="ChooseEnglish">English</span>
<span class="ChooseCymraeg">Cymraeg</span>
</div>
and finally the simplified script :
$(".fancybox").fancybox({
closeClick: true
}).trigger("click"); // you can chain fancybox and trigger methods
$(".ChooseEnglish, .ChooseCymraeg").click(function () {
$.fancybox.close();
}); // bind the same click event to both selectors at once
See JSFIDDLE
NOTE : if you want to prevent the visitor from closing fancybox without choosing any of your ( <span>
) options, then you can add modal:true
instead like :
$(".fancybox").fancybox({
// force to close clicking on any span only
modal: true
}).trigger("click");
See forked JSFIDDLE
The click event is bubbling from the span to the div, so the fancybox gets reopened. You can use .stopPropagation
to prevent bubbling:
$( ".ChooseEnglish" ).click(function(e) {
e.stopPropagation();
$.fancybox.close();
});
$( ".ChooseCymraeg" ).click(function(e) {
e.stopPropagation();
$.fancybox.close();
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.