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.
Related
I have done an auto complete such that when I click the selected result it appends to a div.
image when picking a vehicle
But when I navigate away from that popup and return to it. When I do a search and click the result I want, it appends two values at a go with the second one as empty like in the next image.
the second image with a blank value
How do I prevent this from happening ?
My code is as shown below:
$(function(){
$(".search1").keyup(function() {
var searchid = $(this).val();
var dataString = 'search='+ searchid;
if(searchid!=''){
$.ajax({
type: "POST",
url: "assets/ajax/search1.php",
data: dataString,
cache: false,
success: function(html){
$(".resultgeter").html(html).show();
}
});
}return false;
});
$(document).on('click', ".showing" , function() {
var vhlid = $(this).html();
$(".searchid").append('<div class="choice"><div class="pickVehicle">'+vhlid+'</div><div class="select2-search-choice-close"></div></div>');
$(this).html("");
this.html = "";
$(this).remove();
$(".resultgeter").fadeOut();
return false;
});
$('.search1').click(function(){
$(".resultgeter").fadeIn();
return false;
});
});
I don't know the real solution for this, but a trick might work.
Adding an if statement to make sure vhlid is not blank while appending.
$(document).on('click', ".showing" , function() {
var vhlid = $(this).html();
if(vhlid!=" " || vhlid.length>1) {
$(".searchid").append('<div class="choice"><div class="pickVehicle">'+vhlid+'</div><div class="select2-search-choice-close"></div></div>');
}
$(this).html("");
this.html = "";
$(this).remove();
$(".resultgeter").fadeOut();
return false;
});
I want to use preventDefault() in .each function for collection of buttons and its not working. When I use it with one .click function it works fine but inside .each is not
Whan am I doing wrong?
Here is my .js code
$(document).ready(function() {
var findingStatus = $('#findingStatus').attr('finding-status-type');
var findingLike = $('#finding_like_btn');
var findingDislikeBox = $('.finding_dislike_add');
var findingDislikeCollection = $('.finding_dislike_add_btn')
var findingUnlike = $('#finding_unlike_btn');
var findingDislikeRemoved = $('#finding_dislike_removed');
var alertBox = $('.alert-box').hide();
if (findingStatus == 0) {
findingDislikeBox.show();
findingUnlike.hide();
findingDislikeRemoved.hide();
}
else if (findingStatus == 1) {
findingDislikeBox.hide();
findingUnlike.show();
findingDislikeRemoved.hide();
}
else if (findingStatus == 2) {
findingDislikeRemoved.show();
findingUnlike.show();
findingDislikeBox.hide();
findingLike.hide();
}
findingDislikeCollection.each(function() {
var findingDislike = $(this).clone();
var url = findingDislike.attr("href");
findingDislike.click(function(event) {
event.preventDefault();
$.ajax({
url: url,
type: "POST",
dataType: "json",
success: function(data) {
if (data.profileState == 1) {
$('#dislike_count_btn').text('Odrzuć' + data.DislikeCount);
findingDislikeBox.hide();
findingDislikeRemoved.show();
findingUnlike.show();
//findingUnDislike.show();
//findingUnDislike.attr('disabled', false );
//findingUnDislike.text('Cofnij');
}
else {
alertBox.show();
if ($('.alert-box-msg').length==0) {
$('.alert-area').prepend('<p class="alert-area alert-box-msg">Żeby korzystać z tej funkcji musisz być zalogowany.</p>');
}
findingDislike.attr('disabled', false );
}
},
error: function() {
alert('Problem z serwerem, spróbuj ponownie za kilka minut.');
findingDislike.attr('disabled', false );
}
});
});
});
$('html').click(function (e) {
if (!$(e.target).hasClass('alert-area')) {
$('.alert-box').hide();
findingDislike.attr('disabled', false );
}
});
});
Thanks for answer
You are cloning the element with .clone which means you're not actually attaching an event listener to anything in the DOM. Cloned elements must be manually inserted into the DOM with JavaScript for them to have any effect.
This is not a correct way. Following should work:
findingDislikeCollection.click(function(event){
var findingDislike = $(this);
var url = findingDislike.attr("href");
//AJAX call
event.preventDefault();
});
More details on click event are given here:
https://api.jquery.com/click/
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>
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.
I have a jQuery script that is a search script but also contains functionality to resize an element to the (screen height - 40px) when the window is resized. However, I want to disable the resizing function when a search (AJAX query) is active. Does anyone know how I can do this?
My current code is:
$(document).ready(function(){
$(window).resize(function(){
if($(window).height()<1200){
$("#a").height($(window).height()-40);
}
});
$("form").submit(function(a){
a.preventDefault();
if($("#i").val().length>0){
$.ajax({
type:"get",
url:"search.php?q="+q,
dataType:"html",
success:function(a){
...
}
})
}
})
})
Use .on() and .off()
$(document).ready(function(){
function started(){
if($(window).height()<1200){
$("#a").height($(window).height()-40);
}
$(window).on("resize.name_space",started);
$("form").submit(function(a){
a.preventDefault();
if($("#i").val().length>0){
$(window).off("resize.name_space");
$.ajax({
type:"get",
url:"search.php?q="+q,
dataType:"html",
success:function(a){
$(window).on("resize.name_space",started); ...
}
})
}
})
})
var loading;
...
if($(window).height()<1200 && !loading){
...
loading = true;
$.ajax({
...
complete: function(){
loading = false;
}.
})
}
})
Try this, it adds a check in whilst the ajax is running and will stop the re-sizing from taking place
$(document).ready(function(){
//Create the variable
var check = false;
$(window).resize(function(){
//Is the ajax currently running? This if statement runs if the answer is no
if (check == false && $(window).height()<1200 ) {
$("#a").height($(window).height()-40);
}
});
$("form").submit(function(a){
a.preventDefault();
//Set the variable to true, this stops the resizing above ^^
check = true;
if($("#i").val().length>0){
$.ajax({
type:"get",
url:"search.php?q="+q,
dataType:"html",
success:function(a){
...
},
complete: function() {
//Set back to off once the ajax has finished
check = false;
}
})
}
})
})