Modal backdrop doesn't hide when clicking an element inside it - javascript

On a page I have a modal with few <div class="message-container">. If the user clicks on that element, the page sends AJAX request for new modal. But when I close a new modal, I still have the backdrop from the first modal.
All modals return PHP. I have also tried closing the old modal before opening a new one but that still doesn't help.
Here is the JS code:
$(document).on('click', '.message-container', function () {
var messageId = $(this).attr('data-message-id');
$.ajax({
method: "POST",
data: {
action: 'readMessage',
messageId: messageId
}
}).done(function (ret) {
var obj = jQuery.parseJSON(ret);
if (obj.code == 1) {
$('#messages').modal('hide');
$('.modal-container').html('');
$('.modal-container').html(obj.value);
$('#read-message').modal('toggle');
} else {
}
});
});
$(document).on('click', '.unreadedMessages', function () {
$.ajax({
method: "POST",
data: {
action: 'getMessages'
}
}).done(function (ret) {
var obj = jQuery.parseJSON(ret);
if (obj.code == 1) {
$('.modal-container').html(obj.value);
$('#messages').modal('show');
} else {
var content = '<div class="alert alert-danger" id="messages-alert" role="alert">' + obj.value + '</div>';
}
})
});
unreadedMessages is first.

Not sure if this is exactly what you need, but here is a CSS pattern that I used when I have multiple modals open.
body .modalBlockout ~ .modalBlockout {
opacity: 0 !important;
}
This will hide any extra block out elements, and only shows the first one.

Related

How to make 2 condition in button clicked jquery

Hello is that possible to make two condition from 1 button clicked?
if(unable == 4) {
$("#formitem").submit(function () {
$("#order_4").appendTo("body");
var message = "<?=$message_change_location?>";
var resotid = <?=$restaurant_info["restaurant_id"]?>;
var restoname = "<?=$restaurant_info["restaurant_name"]?>";
var restomenu = "<?=$restaurant_menu?>";
var postal = "<?=$postal?>";
var delivery_no = "<?=$delivery_no?>"
jQuery.ajax({
type: "GET",
url: "/ajax/order_unable",
dataType: 'html',
data: {
message_change_location: message,
restid: resotid,
restname: restoname,
restmenu: restomenu,
postal: postal,
delivery_no: delivery_no,
},
success: function (res) {
$("#order_4_show").html(res);
$("#order_4").modal("show");
}
});
return false;
});
}else if($("#second_notif") == "show"){
$("#formitem").submit(function () {
alert("asdf");
});
I want to make a condition if second_notif is showed, than if i click $("#formitem") for the second times will show the alert. The first click will show pop up windows, and there is not any problem here.
in the pop up windows there is a script to show the second_notif, with this following code :
<script>
$(document).ready(function() {
$("#change_location_2").click(function () {
$(".vendor-heading").hide();
$(".location-header").hide();
$("#order_4").modal("hide");
$("#second_notif").show();
return true;
});
});
</script>
and there in same page on where to show the pop up windows there is a code to show the second_notif too :
$("#change_location").click(function(){
$(".vendor-heading").hide();
$(".location-header").hide();
$("#second_notif").show();
return true;
});
here is the view for the second_notif :
<div id="second_notif" style="display:none;">
<?php $this->load->view('MAIN/'.country_code.'/search');?>
</div>
I can show the pop up windows, and show the second_notif when i clicked formitem button, but when the second_notif has been showed and if i clicked the same button again, why i cant show the alert?
guys can you help me how to show the alert?
p.s alert is not my goal, i will change the alert to other view
please help me guys, thank you (:
First of all, you only need one event handler for this method. You can then move your conditionals into the handler.
Secondly, your condition $('#second-notif') == 'show' will not work, as is will never evaluate to true. To test if an element is visible using jQuery, use the .is(':visible') method. Here's a quick example of what you're looking for:
JSFiddle
Bind the two element in single handler
$("#change_location_2, #change_location").click(function () {
$(".vendor-heading").hide();
$(".location-header").hide();
$("#order_4").modal("hide");
$("#second_notif").show();
return true;
});
how if you add condition to form submit like this ?
$("#formitem").submit(function () {
if(unable == 4) {
$("#order_4").appendTo("body");
var message = "<?=$message_change_location?>";
var resotid = <?=$restaurant_info["restaurant_id"]?>;
var restoname = "<?=$restaurant_info["restaurant_name"]?>";
var restomenu = "<?=$restaurant_menu?>";
var postal = "<?=$postal?>";
var delivery_no = "<?=$delivery_no?>"
jQuery.ajax({
type: "GET",
url: "/ajax/order_unable",
dataType: 'html',
data: {
message_change_location: message,
restid: resotid,
restname: restoname,
restmenu: restomenu,
postal: postal,
delivery_no: delivery_no,
},
success: function (res) {
$("#order_4_show").html(res);
$("#order_4").modal("show");
}
});
return false;
}else if($("#second_notif") == "show"){
alert("asdf");
}
});

jQuery / Ajax Add Class to an LI not working

jQuery / Ajax Add Class to an LI not working. Trying to add the 'open' class to a LI, that opens my 'floating cart' area when an item has been added to the cart. However, the 'open' class just. won't. apply. Not sure why.
I'm also using the Bootstrap framework, and jQuery.
My Code is:
function ShoppingCartAddAJAX(formElement, productNumber) {
formElement = $(formElement);
$.ajax({
type: "POST",
url: "dmiajax.aspx?request=ShoppingCartAddAJAX",
data: formElement.serialize(),
dataType: "json",
success: function (response) {
if (response.Status == "WishListSuccess") {
var url = "productslist.aspx?listName=" + response.listName + "&listType=" + response.listType;
$(location).attr('href', url)
} else if (response.Status == "Success") {
if (response.Status == "Success") {
$.ajax({
type: "GET",
url: "dmiajax.aspx?request=FloatingCart&extra=" + rnd(),
dataType: "html",
success: function (response) {
$('#floating').addClass('open');
var floatingCart = $("ul.dropdown-menu.topcartopen");
if (floatingCart.length == 0) {
floatingCart = $('<ul class="dropdown-menu topcart open"></ul>').insertBefore("#floating-cart");
floatingCart.hoverIntent({
over: function () {},
timeout: 200,
out: function () {
$(this).stop(true, true).filter(":visible").hide("drop", {
direction: "down"
})
}
})
}
floatingCart.html(response);
$("html, body").scrollTop(0);
var floatingCartTbody = floatingCart.find("tbody");
floatingCartTbody.find("tr").filter(":last").effect("highlight", {
color: "#B3B3B3"
}, 3500);
floatingCart.fadeIn()
}
});
if (response.CartItemCount) {
if (response.CartItemCount == "0") {
$("a.cart-tools-total").html("Shopping Cart<span class=\"label label-orange font14\">0</span> - $0.00")
} else {
$("a.cart-tools-total").html("Shopping Cart <span class=\"label label-orange font14\"> " + response.CartItemCount + " Item(s) </span> - " + response.CartItemTotal + " <b class=\"caret\"></b>")
}
}
formElement.find("select option").attr("selected", false);
formElement.find("input:radio").attr("checked", false);
formElement.find("input:checkbox").attr("checked", false);
formElement.find("input:text").val("");
if (formElement.find(".personalization-toggle").length > 0) {
formElement.find(".person-options").hide()
}
if (formElement.find(".attribute-wrap.trait").length > 0) {
formElement.find(".stock-wrap").remove()
}
} else if (response.Error) {
alert(response.Error)
}
}
}
})
}
The line where I'm tring to add it to the LI is:
$('#floating').addClass('open');
The LI is:
<li id="floating" class="dropdown hover carticon cart">
The LI's ID is floating, I figured that'd add the class of 'open' to it. NOPE. For some reason, just not happening.
And, just for the sake of including it, the live environment is here: http://rsatestamls.kaliocommerce.com/
Try changing it to:
$('#floating').attr("class", "open");
Try adding this to your ajax request. It maybe is getting an error:
$.ajax({
type: "GET",
url: "dmiajax.aspx?request=FloatingCart&extra=" + rnd(),
dataType: "html",
success: function (response) {
$('#floating').addClass('open');
var floatingCart = $("ul.dropdown-menu.topcartopen");
if (floatingCart.length == 0) {
floatingCart = $('<ul class="dropdown-menu topcart open"></ul>').insertBefore("#floating-cart");
floatingCart.hoverIntent({
over: function () {},
timeout: 200,
out: function () {
$(this).stop(true, true).filter(":visible").hide("drop", {
direction: "down"
})
}
})
}
floatingCart.html(response);
$("html, body").scrollTop(0);
var floatingCartTbody = floatingCart.find("tbody");
floatingCartTbody.find("tr").filter(":last").effect("highlight", {
color: "#B3B3B3"
}, 3500);
floatingCart.fadeIn()
}
error: function(objAjax,state,exception){
console.log('exception: '+exception+'. State: '+state);
},
});
Then, you will be able to check (at Firebug or other app) if your request is working right.
I suspect you are not correctly selecting the #floating element. Sometimes the element is not visible with only the ID and you must be a little more specific with the selectors.
We would need to see exactly the source for the rendered page to be sure what to put, but try doing this:
Add a button onto the page that you can use to test if you found the correct selector:
<input id="mybutt" type="button" value="Tester Click">
Next, add this javascript/jquery code and -- one at a time -- comment the test selector that failed, and uncomment the next attempt:
$('#mybutt').click(function() {
var test = $("#floating");
//var test = $("li #floating");
//var test = $("ul li #floating");
//var test = $("ul > li #floating");
if ( test.length > 0 ) {
alert('Found this: ' + test.attr('id') );
}
});
Once you are certain that you have the correct selector, then your original code -- using the correct selector -- should work:
$('#the > correctSelector').addClass('open');
Note: the above code uses jQuery, so ensure you are including the jQuery library on the page (usually between the <head> tags, like this:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>

Replace button before ajax call and then revert back after call

I have a button on my webpage that is generated like this :
<div class="btn2" id="btPost" onclick="$('#Delete').val('False'); ValidateFormAndAjaxSubmit('frmEditPost', this);" onmousedown="this.className='btn2_click';" onmouseout="this.className='btn2';" onmouseover="this.className='btn2_hover';" onmouseup="this.className='btn2_hover';">
<span>Posta</span>
</div>
When I have this javascript :
function ValidateFormAndAjaxSubmit(formId, callingElement) {
if (IsNotDblClick(callingElement.id)) {
var _form = $("#" + formId);
var validator = _form.validate();
var anyError = false;
anyError = !_form.valid();
if (anyError) {
window.latestClick = '';
return false; // exit if any error found
}
$.post(_form.attr("action"), _form.serialize(), function (data) {
if (data.success && data.redirectUrl.length > 0) {
window.location.href = data.redirectUrl;
}
else {
var isValid = validateResponse(_form, data);
window.latestClick = '';
}
})
}
}
This is working fine, but the problem is that I want to show the enduser that the form is loading. The best solution might be to simple remove the callingElement from the webpage and replace it with a temporary disabled(special CSS) button. The button needs to return then the ajax method is done.
I know about this :
$("#regTitle").html("Hello World");
But it is only replacing inner part of the div and I do also need to store the current markup to beable to go back when the ajax call is done.
It would also be good if the text within the span is placed also on the temporary button.
The question is how I do this as simple as possible?
Try this
$.ajax({
'type': 'POST',
'url': _form.attr("action"),
'data': _form.serialize(),
'beforeSend': function() {
$('.btn2').hide();
$('#regTitle').html('Loading ...');
$('#regTitle').show();
},
'success': function() {
$('.btn2').show();
$('#regTitle').hide();
},
'error': function() {
$('.btn2').show();
$('#regTitle').html('Error ...');
}
});
This is how I solved it :
Generate extra hidden div under the botton like this :
<div class="loadingDiv" id="loadingDiv_btPost"></div>
with the following css :
.loadingDiv {
float: left;
display: none;
height: 26px;
width: 60px;
background: url("images/animations/ajaxLoader.gif") no-repeat;
background-position: center center;
}
Then changed the javascript like this :
function ValidateFormAndAjaxSubmit(formId, callingElement) {
if (IsNotDblClick(callingElement.id)) {
var _form = $("#" + formId);
var validator = _form.validate();
var anyError = false;
anyError = !_form.valid();
if (anyError) {
window.latestClick = '';
return false; // exit if any error found
}
$('#' + callingElement.id).hide();
$('#loadingDiv_' + callingElement.id).show();
$.post(_form.attr("action"), _form.serialize(), function (data) {
$('#loadingDiv_' + callingElement.id).hide();
$('#' + callingElement.id).show();
if (data.success && data.redirectUrl.length > 0) {
window.location.href = data.redirectUrl;
}
else {
var isValid = validateResponse(_form, data);
window.latestClick = '';
}
})
}
}

jquery .on() is not triggering

I have the following code:
console.log($(".resultLike"));
$(".resultLike").on("click", function (event) {
alert('test');
event.stopPropagation();
alert('test1');
value['clicked'] = 1;
$.ajax({
url: 'scripts/php/userProfile.php',
data: {
action: value
},
type: 'post',
dataType: 'json',
success: function (profileData) {
if (profileData == 'removed') {
$(me).children('.resultInside')
.children('.resultData')
.children('.resultLike').html('Favourite?');
} else if (profileData == 'notLoggedIn') {
$(me).children('.resultInside')
.children('.resultData')
.children('.resultLike').html('Login to add');
} else {
$(me).children('.resultInside')
.children('.resultData')
.children('.resultLike').html('un-Favourite');
}
}
});
});
My expectations is that when you click on the div resultLike, then it will preform the function(). However, it does nothing. I have two alert() calls in there, and neither is being called. The output of console.log() is as follows:
[
<div class=​"resultLike searchBarGameLike">​</div>​
]
That proves it's being put on the page. Any help would be appreciated, thanks.
EDIT:
I think it should be mentioned that I'm actually using two .on() events.
This is actually all my code. The issue is around the
$("body").on("click", ".resultLike", function(){
Line, it's not working.
$searchedGamesContainer.on(
"click",
".box",
function(event){
if(!$displayLock){
$displayLock = true;
var description;
var user_id;
if($(this)[0].style.width == '75%'){
var org_img = $(this).children(".resultInside").find("img").attr("src");
$(this).children(".resultInside").append("<img src='"+org_img+"' id='imgId'/>");
$(this).children(".resultInside").css('height','auto');
$(this).css('width', '18%');
$(this).css('height', 'auto');
$(this).find(".resultData").fadeOut('fast');
setTimeout(function(){$searchedGamesContainer.masonry('reload');},300);
setTimeout(function(){$displayLock = false;},1000);
}else{
var me = this;
var pos;
largeImage= new Image();
value['name']=$(me).find("p").html();
oldImage = $(this).find("img").attr("src");
for(var i = 0; i<$searchBarGames.length; i++){
if($searchBarGames[i][5] == value['name']){
pos = i;
break
}
}
description = $searchBarGames[pos][2];
$(me).find("img").hide();
largeImage.src = $searchBarGames[pos][4];
$(me).find("img").attr("src",largeImage.src);
$(me).children(".resultInside").css('height','400px');
$(me).css('width', '75%');
$(me).children(".resultInside").html("\
<div class='resultData'>\
<div class='resultImg'><img src='"+ largeImage.src +"'></div>\
<div class='resultName'>" + value['name'] + "</div>\
<div class='resultDesc'>" + description +"</div>\
<div class='wikiLink searchBarGameWiki'><a href='http://wikipedia.org/wiki/" + value['name'] + "'>Wikipedia</a></div>\
<div class='resultLike searchBarGameLike'></div>\
</div>");
value['clicked']=0;
$.ajax({
url:'scripts/php/userProfile.php',
data:{action:value},
type: 'post',
dataType: 'json',
success:function(profileData){
//logic
}
});
console.log($(".resultLike"));
$("body").on("click", ".resultLike", function(){
alert('test');
event.stopPropagation();
alert('test1');
value['clicked']=1;
$.ajax({
url:'scripts/php/userProfile.php',
data:{action:value},
type: 'post',
dataType: 'json',
success:function(profileData){
//logic
}
});
}
);
}
}
}
);
try
$("body").on("click", ".resultLike", function(){
// your code goes here.
});
Your implementation will likely not be bound if the div.resultLike is added dynamically
This problem actually ended up being completely because of CSS.
For the div element I wanted the alerts on, I had markup to look like a button.
However, I noticed this:
.resultLike:active {
position:relative;
top:1px;
z-index:1235;
}
I'm not 100% why, but I think this was actually changing where the button was when clicking it. Meaning as soon as it was active, it wasn't where your mouse was. I could be wrong, but this fixed it.

Jquery and CSS preforming strangely

I've this section of code (I'll point out where I'm confused, just added that huge wall to incase anyone wanted to really dig in).
anyway, the behaviour is to display these boxes, when you click on a box, the box expands, and displays more information. this works 70% of the time, however, it seems when an image is not chached, when you click the box again to minimize it, it starts to minimize, then pops back out. I'm wondering if this has something to do with the line: if($(this)[0].style.width == '70%'){
If this isn't enough, feel free to ask, and if you want to attempt to replicate the issue:
http://newgameplus.nikuai.net/
Try searching a few games, and clicking on the results. (That's only if what I"m saying isn't making sense though)
Thank you.
$container.on("click", ".box", function (event) {
var description;
var user_id;
var org_img = $(this).find("img").attr("src");
if ($(this)[0].style.width == '70%') {
$(this).find("img").attr("src", org_img);
$(this).css('width', '18%');
$(this).find(".resultData").fadeOut('slow');
$container.masonry('reload');
} else {
var me = this;
value['name'] = $(me).find("p").html();
oldImage = $(this).find("img").attr("src");
$.ajax({
url: 'scripts/php/fetchResultsData.php',
data: {
action: value
},
type: 'post',
dataType: 'json',
success: function (data) {
description = data[0][2];
for (var i = 0; i < $test.length; i++) {
if ($test[i][1][2]['name'] == value['name']) {
pos = i;
break;
}
}
$(me).find("img").attr("src", data[0][4]);
$(me).css('width', '70%');
$(me).append("\
<div class='resultData'>\
<div class='resultName'>" + value['name'] + "</div>\
<div class='resultDesc'>" + description + "</div>\
<div class='reasonDataTitle'> Similar tropes between this game and the searched games </div>\
<div class='reasonData'>" + $test[pos][4] + "</div>\
<div class='wikiLink'><a href='http://wikipedia.org/wiki/" + value['name'] + "'>Wikipedia</a></div>\
<div class='resultLike'></div>\
</div>");
value['clicked'] = 0;
$.ajax({
url: 'scripts/php/userProfile.php',
data: {
action: value
},
type: 'post',
dataType: 'json',
success: function (profileData) {
if (profileData == 'alreadyAdded') {
$(me).children('.resultData').children('.resultLike').html('un-Favourite');
} else if (profileData == 'notLoggedIn') {
$(me).children('.resultData').children('.resultLike').html('Login to add');
} else {
$(me).children('.resultData').children('.resultLike').html('Favourite?');
}
}
});
$(me).on("click", '.resultLike', function (event) {
event.stopPropagation()
value['clicked'] = 1;
$.ajax({
url: 'scripts/php/userProfile.php',
data: {
action: value
},
type: 'post',
dataType: 'json',
success: function (profileData) {
if (profileData == 'removed') {
$(me).children('.resultData').children('.resultLike').html('Favourite?');
} else if (profileData == 'notLoggedIn') {
$(me).children('.resultData').children('.resultLike').html('Login to add');
} else {
$(me).children('.resultData').children('.resultLike').html('un-Favourite');
}
}
});
});
$container.masonry('reload');
}
});
}
});
I would suspect there's a race condition in your effects code. jQuery effects run asynchronously, so $container.masonry('reload') will get called when fadeOut starts rather than after it's finished. If the jQuery Masonry plugin affects the display of any blocks you're fading out (and its documentation indicates that's highly possible), that race condition of both functions running at once will cancel the first one out.
To work around this, try running the Masonry reload in a callback function to fadeOut, like so:
$(this).find(".resultData").fadeOut('slow', function () {
$container.masonry('reload');
});
The reason it happens only sometimes is based on the speed of how things are loading, which would explain why it only happens when certain assets aren't cached.

Categories