user3767554 user3767554 - 3 months ago 16
jQuery Question

javascript/Jquery pop up - only open one pop at a time

I have 3 separate scripts for 3 pop ups, Im sure there is a better way to structure these into one script? I also want to be able to only open one pop up at a time, so if .popup-new is active and i click to open .popup-new-b then .popup-new will automatically close. Any help would be much appreciated.

<script>
$(document).ready(function () {
$(".popup-trigger").click(function () {
$(".popup-new").fadeIn(300);

});

$(".popup-new > span, .popup-new").click(function () {
$(".popup-new").fadeOut(300);
});
});
</script>

<script>
$(document).ready(function () {
$(".popup-trigger-b").click(function () {
$(".popup-new-b").fadeIn(300);

});

$(".popup-new-b > span, .popup-new-b").click(function () {
$(".popup-new-b").fadeOut(300);
});
});
</script>

<script>
$(document).ready(function () {
$(".popup-trigger-c").click(function () {
$(".popup-new-c").fadeIn(300);

});

$(".popup-new-c > span, .popup-new-c").click(function () {
$(".popup-new-c").fadeOut(300);
});
});
</script>

Answer

Since I cannot see your HTML. I have added some with CSS. I hope this is what you are looking for. Ofcourse I could've asked clarify but I do not have enough reputation to add comment :(

$('button').click(function(){
    $('.popup').removeClass('popped');
    $('#popup-new'+$(this).attr('class')).addClass('popped');
 });
.popup{
   position:fixed;
   width:70%;
   height:70%;
   top:50%;
   left:50%;
   margin-top:-5%;
   margin-left:-35%;
   background-color:#ccc;
   z-index:100;
   display:none;
}
.popped{
   display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div id="popup-new" class="popup">HI I am POPUP NEW</div>
<div id="popup-new-b" class="popup">HI I am POPUP-NEW-B</div>
<div id="popup-new-c" class="popup">HI I am POPUP-NEW-C</div>

<button class="">Pop up New</button>
<button class="-b">Pop up New B</button>
<button class="-c">Pop up New C</button>

Comments