Ajax-loaded popup image is not always clearing when div emptied - javascript

I made an image previewer that gives a popup of an image when you hover on that link. It works but sometimes it will fail to .empty the div when I stop hovering over the link. I will ocassionally get the previous image, the error text, or two images. If I hover again it is fixed. This happens maybe 10% of the time. Also I can't get the height of the div. I don't know if this is also related.
$('<div/>',{
'id' : 'popup'
}).appendTo('body');
function showError() {
$('<div/>').text('Picture Not Found').appendTo('#popup');
$('#popup').show();
};
function getImage() {
$.ajax({
type: 'GET',
url: link,
error: function(){
showError();
},
success: function(data) {
var styleText = $('style', data).text();
var imageRegex = /background-image: url\('[^']+/;
var imageMatch = styleText.match(imageRegex);
if (imageMatch) {
var image = imageMatch[0].replace(/background-image: url\('/, '');
$('#popup').append('<img src="' + image + '" style="padding:0px" alt="">');
} else {
showError();
};
}
});
};
$('a').filter(function() {
return /users\/\d+\/pictures/.test(this.href);
}).removeAttr('title').hover(function(e) {
link = this.href.replace('http://', 'https://');
getImage();
$('#popup').show();
height = $('#popup').outerHeight();
console.log(height);
}, function() {
$('#popup').empty().hide();
})
});

Looks like it was an issue with triggering a hover event when passing over the link quickly. Seems to be fixed by adding a delay to the hover.
Here is a link to a guide that helped.
http://jelaniharris.com/2008/adding-a-delay-to-jquery-functions/
I also changed it to a separate div for the error message so I could just change the src of the image rather than empty the div. I think that makes it a little faster.

Related

jQuery: Uncaught Error: Syntax error, unrecognized expression: (bunch of photo caption text data)

I am attempting to add text from a jQuery array at a given point to my webpage. The page is set up so that when I click on a thumbnail, a larger image and caption data are to show on the page, however the caption text is not showing. $(caption[this.id]).text().appendTo('#images'); is where the error comes from, though if I do a simple DOM.write with the (caption[this.id]).text(), the words will show on the page.
// App variables
var filename = [];
var caption = [];
var id = [];
var counter = 0;
var thumbs = $([]);
var images = $([]);
//Make an AJAX call to load the XML file data
$.ajax({
url: 'gallery.xml',
dataType: 'xml',
success: function (data) {
$(data).find('gallery').each(function () {
// Gather the image filenames
$(data).find('image filename').each(function () {
counter++;
id.push(counter);
filename.push($(this).text());
});
//console.log(filename);
// Gather the image captions
$(data).find('image caption').each(function () {
caption.push($(this).text());
});
});
// Run the thumbnail loading procedure when the AJAX call has completed
loadThumbs();
loadImages();
},
error: function () {
// Failure alert if XML was not loaded
alert("XML file couldn't load...");
}
});
// Loop through filename list and create large image for each entry
var loadImages = function() {
$.each(filename, function (_, src) {
images = images.add(
$('<img />', {src: 'images/' + src, class: 'largeImage', height: '100px', width: '100px'})
);
});
// Add first image to default
$(images[0]).appendTo('#images')
};
// Do some shit when image is clicked...
$( document ).on( "click", "img", function() {
// Empty viewing DIV and create a new large-scale version of the image for viewing
$('#images').empty();
$(images[this.id]).appendTo('#images');
//THIS IS WHERE ERROR COMES FROM
// Add text to <span> to solve error?
$(caption[this.id]).text().appendTo('#images');
});
The error is specifically:
I can add all of the JS code if there is not enough here to understand. Thanks in advance.
You're passing the caption text to jQuery:
$(caption[this.id])
The library is trying to parse it as a CSS selector, and it can't so it throws the error.
You could do several things to make it work, and your suggestion in the comment is a good one:
$("<span/>", { text: caption[this.id] }).appendTo("#images");

replacing css background image after uploading that photo via Ajax

I have an element which when I click It opens input dialog and uploads the selected photo. the server responds the request with 4 items as a JSON OBJECT : NAME,TYPE,HEIGHT,WIDTH.
The thing I want is after a successful ajax upload process, reload/refresh the element background with the newly uploaded photo. so far I've don these:
JS:
$(document).ready(function() {
$("input[name!='photo_1']").parents('.fileinput-wrapper').find(".label").remove();
$("input[type=file]").on('change',function(){
$(this).parents('label').find('.fileinput-preview').css('background','url(http://localhost/project/assets/images/ajax-loader.GIF) no-repeat center center');
var selectedElement = this;
var name = $(this).attr('name').toString();
$('#upload').ajaxSubmit({
dataType:'json',
data: {name:name},
beforeSubmit:function(){
$(selectedElement).parents('label').find('input[type=file]').attr('disabled','disabled');
},
success: function(data) {
$(selectedElement).parents('label').find('.fileinput-preview').css('background',"url('http://localhost/project/assets/images/loading.png') no-repeat center center");
$.each(data, function(index, item) {
$(selectedElement).parents('label').find('.fileinput-preview').css('background',"url('http://localhost/project/uploads/"+ item.NAME +") no-repeat center center");//**replacing part**
});
$(selectedElement).parents('label').find('input[type=file]').removeAttr('disabled');
return false;
},
error : function(xhr) {
alert(xhr.responseText);
return false;
}
});
});
});
the thing is it replaces the background right but the image doesn't load and shows a blank. What should I do?
You are missing a single ':
.css('background',"url('http://localhost/project/uploads/"+ item.NAME +")
Should be
.css('background',"url(http://localhost/project/uploads/"+ item.NAME +")
The url parameter does not need '', url(path/to/file.jpg) works fine. You are only setting one, though. Also, does item.name contain the file extesion?
Check with the dom inspector what url is being set after the success, or do a console log of the full string

Dynamic div content fades before it should

I know that jQuery has a tooltip object, but I wanted to get a few things straight making my own for launching into using something that I didn't fully understand. I want the content to be displayed dynamically, but first I tried my hand using:
css: .hiddenEl{display:none;}
$(document).ready(function () {
$('#showElement').click(function () {
getText()
});
function getText() {
$.ajax({
//...ajax options
success: function (data) {
//if I use this line of code when a div with
// class hiddenEl is already on the page, it works
$('.hiddenEl').text(data.d).fadeToggle();
//when I create the div dynamically it fades in
//,and immediately fades back out.
//var $div = $('<div>').addClass('.hiddenEl').text(data.d).appendTo('body').fadeToggle();
},
error: function (xhr) {
console.log('failed: ' + xhr.status);
}
});
}
});
I'd like to know why in the version where I'm filling the div with dynamic content that it fades back out once the animation is done and in the first one it works as expected (which means the div is hidden on the second click) and how I can fix it. Secondly, I'd like to see how my version compares to someone else's who might write their own custom tooltip
EDIT: here's a non-AJAX way that's doing the same thing.
$(document).ready(function () {
$('#showElement').click(function () {
getText()
});
var array = ['first', 'second', 'third'];
function getText() {
$.ajax({
success: function (data) {
console.log('success');
//if I use this line of code when a div with
// class hiddenEl is already on the page, it works
// $('.hiddenEl').text(data.d).fadeToggle();
//when I create the div dynamically it fades in
//,and immediately fades back out.
var $div = $('<div>').addClass('.hiddenEl').text(array).appendTo('body').fadeToggle();
},
error: function (xhr) {
console.log('failed: ' + xhr.status);
}
});
}
});

AJAX call requires double click

I've created a function which loads content and writes into html. For some reason the function is displayed after two clicks instead of one. Any idea how to make it so it load and display the info with just one click?
function getFuncDoc(funcName, targetDivId) {
var webServiceCall = funcName;
$.ajax({
type: "get",
url: webServiceCall,
success: function(doc) {
$('#' + targetDivId).load(doc, function(){
$('#' + targetDivId).toggle(
function() {
$('#' + targetDivId).css('padding', '10px');
$('#' + targetDivId).html(doc);
});
});
},
error: function(request, status, error) {
return 'Error';
}
});
}
Check if the targeted element (targetDivId) has display:none before the toggle() is triggered.
If that's not the case, then you'll need to add this attribute to your element in CSS.
toggle()-ing an element with display:block or display:inline or display:inline-block will hide the element and set its attribute to display:none, hence why you need to trigger it twice for the content to be shown.
Here is a live demo.

Change css of first div after live click

I want to be able to change the css of a div after I have clicked span.submit-comment.
How would I go about to change the css of that div.
I tried putting the following in the success part of the script:
$('div.news-comment:first').css("background-color", "#000");
But the div just flashes black (as I click) because it's inside the click function. I want the css to persist untill I refresh the page.
Any ideas?
// post news comment
$('span.submit-comment').live('click', function() {
var commentname = $('input#commentname').val();
var commentcontent = $('textarea#commentcontent').val();
var newsid = $('span.view-comments').attr('id');
var datastring = 'commentname=' + commentname + '&commentcontent=' + commentcontent + '&newsid=' + newsid;
$.ajax({
type: "POST",
url: "ajax/post_news_comment.php",
data: datastring,
success: function(){
$('div#news-comments').load('ajax/get_news_comments.php?news_id=' + newsid);
}
});
});
If the comment you are changing the background on is in the #news-comments div you are replacing it with the loaded html from get_news_comments.php in your .ajax callback. No matter where you put your js the element will be replaced.
If so, adding it in a callback for the load in your success function should be ok.
Your css script is ok, but just place it after load function.
Just add a return false at the end of the function for the button click, or pass in the value e and put e.preventDefault(); at the begining or end of the function.
e.g.
$('span.submit-comment').live('click', function(e) {
e.preventDefault();
// your other code.
return false;
});

Categories