Dynamic div content fades before it should - javascript

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);
}
});
}
});

Related

jQuery .bind('show') not working appropriately when element is shown via jQuery

I have a snippet in my project similar to the one seen below:
$('#field').change(function() {
var thisCondition = $(this).val();
if(thisCondition) {
$('#this_container').fadeIn();
}
});
The above snippet is working. When thisCondition evaluates to true, the container does fade in. However, I also have the snippet below that is not functioning as expected. It binds to show so that when the container fades in an event will be triggered:
$('#this_container').bind('show', function() {
$.ajax({
...
});
});
Shouldn't the snippet above react to line 5 in the change event handler? Why is the bind method not triggering?
Confirmed that show is not a valid nor jQuery-triggered event.
But you can trigger it yourself!
Try something like this :
$('#this_container').fadeIn("slow", function() {
$(this).trigger("show");
});
The show is not a valid event, neither is triggered by jQuery. You need to construct your script in a different way altogether:
$('#field').change(function() {
var thisCondition = $(this).val();
if(thisCondition) {
$.ajax({
success: function () {
$('#this_container').fadeIn();
}
});
}
});
So, you can try to bring the AJAX content, and upon a successful request, you can show the container.
try to use :
$('#this_container').fadeIn( "slow", function() {
// Animation complete
$.ajax({
...
});
});

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

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.

Call jquery function when one function completes

So I have a jquery click function assigned to an on/off toggle. Very simple script:
$('.on-off').on('click', function(e) {
e.preventDefault();
var $this = $(this);
$this.find('.slider').toggleClass('active');
});
We have two versions of this toggle. One toggles instantly when clicked and then we submit the value when clicking next(aka submit).
Our other one calls a jquery ajax function that toggles on success and upon success if it is a specific message code that is defined on the backend.
jQuery.ajax({
url: url,
type: 'POST',
dataType: 'json',
cache: false,
data: {'requestType': requestType},
success: function(message) {
if(message.STATUS=='2000'){
if(currentButtonClicked=='dashboardChargingButton'){
if($('#dashboardChargingButton').html()==startCharge)
$('#dashboardChargingButton').html(stopCharge);
else
$('#dashboardChargingButton').html(startCharge);
}
if(currentButtonClicked=='invokeChargingButton'){
$( "#invokeChargingButton .slider" ).toggleClass( 'active');
}
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status + " - " + xhr.statusText);
}
});
}
As you can see I have to toggle the class again using the same code but with direct targeting.
The on off toggles of this type have an onclick inside the actual html calling the function that handles this ajax.
My goal is to have my first set of code the one that targets the element and toggles the class to do all of this, but dynamically to where we don't have to call a function everytime.
Conceptually what I thought is:
$('.on-off').on('click', function(e) {
e.preventDefault();
var $this = $(this);
if (!$this.attr('onclick')) {
$this.find('.slider').toggleClass('active');
} else {
var clickFunction = $this.attr('onclick');
call the clickFunction
if (clickfunction = true) {
$this.find('.slider').toggleClass('active');
}
}
});
What this would do is grab the onclick, but not call it until I specify. And inside the ajax request instead of toggling I would just return true.
This might not be the best method. I am just trying to ecapsulate everything to limit the amount of code as well as make all the dom changes for those elements in one spot for any potential defects.
Here is a link to a basic fiddle of the on/off toggle.
Fiddle
I hope I explained everything in good enough detail.

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.

Assign dynamic div id from js var

I am having trouble selecting a div with jQuery after assigning the id to a Javascript variable:
$(function() {
$(".do").live("click",function()
{
var id = $(this).attr("id");
$.ajax({
//reload div using js var id
$('id').fadeOut('fast').load('http://example.com/get.php').fadeIn("slow");
});
return false;
});
});
When I call a static div it works just fine like this:
$('#staticdiv').fadeOut('fast').load('http://example.com/get.php').fadeIn("slow");
How can I select a div from a Javascript variable containing its id?
*EDIT
Here is an example if the divs:
Button to engage reload
click to reload
DIV to reload:
<div id="12">to be refreshed</div>
keep in mind the "12" us dynamic and could be any variable.
You can do that using this:
$("#"+id).fadeOut() // ...
However, I wouldn't recommend doing it that way (it won't work on things without IDs); try this instead (which should work on things without IDs):
$(".do").live("click", function() {
var me = $(this);
$.ajax({
// ...
success: function(data) {
me.fadeOut('fast').load('http://example.com/get.php').fadeIn("slow");
}
// ...
});
return false;
});
Additionally, I'm not sure if you really want that .fadeOut().load().fadeIn() chain; the load will not wait for the fadeOut to finish and the fadeIn will not wait for the load to finish (although the fadeIn will wait for the fadeOut to finish). If you have problems with that, you should try this:
me.fadeOut('fast', function() {
me.load('http://www.example.com/get.php', function() {
me.fadeIn('slow');
});
});
Aren't you supposed to use the variable id instead of string 'id'.
As follows:
$('#'+id).fadeOut('fast').load('http://example.com/get.php').fadeIn("slow");

Categories